This question already has answers here:
How are the points in CSS specificity calculated
(7 answers)
Closed 3 years ago.
When defining a CSS class for table cells, I would expect to say td.classname. However, I have seen sample code saying table td.classname and a couple of the answers to How to apply style classes to td classes? say table tr td.classname. All variants seem to produce the same results in Chrome.
What's the difference, and which is preferable?
What's the difference?
Specificity. The browser will apply ALL the styles that match. They are generally applied in order of specificity (from least to most). The higher the specificity of a CSS selector, the greater the likelihood its declarations are used over another CSS rule's declarations.
When calculating specificity the rules are essentially:
Inline styling wins (1,0,0,0 points)
For each ID apply 0,1,0,0 points
For each class, pseudo-class or attribute selector apply 0,0,1,0 points
For each element reference, apply 0,0,0,1 point
Total them up for your selector as if they were a number. 1020 trumps 0123.
In this demo you can see how the final applied style is taken from several declarations. The most specific rules override any less specific ones that came before it:
td {color:#ccc; font-size:20px;}
.me {color:red; background:cyan;}
td.me {color:blue; font-weight:bold;}
tr td.me {color:pink; border:1px solid #7799aa;}
table tr td.me {color:orange;}
<table>
<tr><td>1</td><td class="me">2</td></tr>
</table>
Which is preferable?
It depends on how targeted your styles are meant to be. Are you trying to style all <p>s or just one? Is it a global font style or just for certain element? etc. For global styling use element references and pseudo selectors. When you have specific multiple instances use classnames. Where you have a one-off case use an ID (or a class). For example: You could style all your buttons with low specificity... button {background:grey;} ...and override it with additional specificity: button.warning {background:red;}. Be no more specific than you must be! (You might need to override a style later.)
Further reading:
https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity
https://css-tricks.com/specifics-on-css-specificity/
https://www.codecaptain.io/tools/css-specificity-calculator
The CSS syntax table td.classname means any <td class="classname"> tag inside a <table>, and table tr td.classname means any <td class="classname"> tag within a <tr> within a <table>.
Since every table cell is normally inside a table row inside a table, they are nearly synonyms. If there’s any esoteric exception to that, it must not be relevant to that particular HTML document. This would, however, exclude a <th>—if you only use that classname for this one purpose, you might just as easily write .classname.
Related
I'm trying to figure out why one of my css classes seems to override the other (and not the other way around)
Here I have two css classes
.smallbox {
background-color: white;
height: 75px;
width: 150px;
font-size:20px;
box-shadow: 0 0 10px #ccc;
font-family: inherit;
}
.smallbox-paysummary {
#extend .smallbox;
font-size:10px;
}
and in my view I call
<pre class = "span12 pre-scrollable smallbox-paysummary smallbox ">
The font (The overlapping element) shows up as 10px instead of 20 - could someone explain why this is the case?
There are several rules ( applied in this order ) :
inline css ( html style attribute ) overrides css rules in style tag and css file
a more specific selector takes precedence over a less specific one
rules that appear later in the code override earlier rules if both have the same specificity.
A css rule with !important always takes precedence.
In your case its rule 3 that applies.
Specificity for single selectors from highest to lowest:
ids (example: #main selects <div id="main">)
classes (ex.: .myclass), attribute selectors (ex.: [href=^https:]) and pseudo-classes (ex.: :hover)
elements (ex.: div) and pseudo-elements (ex.: ::before)
To compare the specificity of two combined selectors, compare the number of occurences of single selectors of each of the specificity groups above.
Example: compare #nav ul li a:hover to #nav ul li.active a::after
count the number of id selectors: there is one for each (#nav)
count the number of class selectors: there is one for each (:hover and .active)
count the number of element selectors: there are 3 (ul li a) for the first and 4 for the second (ul li a ::after), thus the second combined selector is more specific.
A good article about css selector specificity.
Here's a compilation of CSS styling order in a diagram, on which CSS rules has higher priority and take precedence over the rest:
Disclaimer: My team and I worked this piece out together with a blog post (https://vecta.io/blog/definitive-guide-to-css-styling-order) which I think will come in handy to all front-end developers.
What we are looking at here is called specificity as stated by Mozilla:
Specificity is the means by which browsers decide which CSS property
values are the most relevant to an element and, therefore, will be
applied. Specificity is based on the matching rules which are composed
of different sorts of CSS selectors.
Specificity is a weight that is applied to a given CSS declaration,
determined by the number of each selector type in the matching
selector. When multiple declarations have equal specificity, the last
declaration found in the CSS is applied to the element. Specificity
only applies when the same element is targeted by multiple
declarations. As per CSS rules, directly targeted elements will always
take precedence over rules which an element inherits from its
ancestor.
I like the 0-0-0 explanation at https://specifishity.com:
Quite descriptive the picture of the !important directive! But sometimes it's the only way to override the inline style attribute. So it's a best practice trying to avoid both.
The order in which the classes appear in the html element does not matter, what counts is the order in which the blocks appear in the style sheet.
In your case .smallbox-paysummary is defined after .smallbox hence the 10px precedence.
First of all, based on your #extend directive, it seems you're not using pure CSS, but a preprocessor such as SASS os Stylus.
Now, when we talk about "order of precedence" in CSS, there is a general rule involved: whatever rules set after other rules (in a top-down fashion) are applied. In your case, just by specifying .smallbox after .smallbox-paysummary you would be able to change the precedence of your rules.
However, if you wanna go a bit further, I suggest this reading: CSS cascade W3C specification. You will find that the precedence of a rule is based on:
The current media type;
Importance;
Origin;
Specificity of the selector, and finally our well-known rule:
Which one is latter specified.
Also important to note is that when you have two styles on an HTML element with equal precedence, the browser will give precedence to the styles that were written to the DOM last ... so if in the DOM:
<html>
<head>
<style>.container-ext { width: 100%; }</style>
<style>.container { width: 50px; }</style>
</head>
<body>
<div class="container container-ext">Hello World</div>
</body>
...the width of the div will be 50px
AS is state in W3:
W3 Cascade CSS
the orden that different style sheet are applied is the following (quote from W3 cascading section):
user agent declarations
user normal declarations
author normal declarations
author important declarations
user important declarations
More information about this in the referred W3 document
Element, Pseudo Element: d = 1 – (0,0,0,1)
Class, Pseudo class, Attribute: c = 1 – (0,0,1,0)
Id: b = 1 – (0,1,0,0)
Inline Style: a = 1 – (1,0,0,0)
Inline css ( html style attribute ) overrides css rules in style tag and css file
A more specific selector takes precedence over a less specific one.
Rules that appear later in the code override earlier rules if both have the same specificity.
In a simple and short way, one should keep in mind the two things below:
Inline CSS has a higher priority than embedded and external CSS.
So final Order is: Value defined as Important > Inline > id nesting > id > class nesting > class > tag nesting > tag
This question already has answers here:
Understanding CSS selector priority / specificity
(4 answers)
Closed 5 years ago.
If I declare in my css file(or inside <style> </style> tags) firstly the id of element and then the classname of the same element, then the id styling will be applied, regardless the fact that classname is the latest one in order.
I want to know why this is happening and if it has some naming, please do tell.
Just to make it more clear, take a look at this example, please:
div {
height:100px;
width:150px;
border:1px solid #000;
margin:0 auto;
}
#theID {
background:#090;
}
.theCLASS {
background:#00F;
}
<div id="theID" class="theCLASS"></div>
This is to do with the complicated world of "Specificity"...
ID's are more specific than classes and take precedence over them. This is because ID's have to be UNIQUE on every page...so they are by nature very specific. Classes can appear multiple times.
Learning how this works is fundamental to coding CSS. Some people say you should try to avoid using ID's altogether as they are so specific they tend to cut down reuse.
A rule of thumb might be to use ID's to identify large sections of your page, or important items and classes to attach styles to the other things.
These days with html5 we have <section>, <header> and <footer> whereas we used to use div's for those (with ID's normally) so these days the ID is used less than ever since we can target those things directly.
However consider ID-ing sections: <section id="mainContent"> for example is a fairly standard thing to do.
There are no RULES about how to specifically (excuse the pun) use ID's and classes. Just conventions that have built up over time.
see: https://developer.mozilla.org/en/docs/Web/CSS/Specificity ... here is a section:
The concept
Specificity is the means by which browsers decide which CSS property
values are the most relevant to an element and, therefore, will be
applied. Specificity is based on the matching rules which are composed
of different sorts of CSS selectors.
How is it calculated?
Specificity is a weight that is applied to a given CSS declaration,
determined by the number of each selector type in the matching
selector. When specificity is equal to any of the multiple
declarations, the last declaration found in the CSS is applied to the
element. Specificity only applies when the same element is targeted by
multiple declarations. As per CSS rules, directly targeted element
will always take precedence over rules which an element inherits from
its ancestor.
It carries more specificity
CSS applies vastly different specificity weights to classes and IDs.
In fact, an ID has infinitely more specificity value! That is, no
amount of classes alone can outweigh an ID.
CSS Tricks - Specifics on CSS Specificity
Further Reading:
CSS Tricks - The Difference Between ID and Class
MDN - Specificity
Selector Types
The following list of selector types increases by specificity:
Type selectors (e.g., h1) and pseudo-elements (e.g., :before).
Class selectors (e.g., .example), attributes selectors (e.g.,
[type="radio"]) and pseudo-classes (e.g., :hover).
ID selectors (e.g., #example).
html....
<div class="one two">test</div>
<div class="two one">test</div>
css....
.one.two{
color: red;
}
.two.one{
color: blue;
}
I was supposing to have the first div color to be red and second div color to be blue, but it's taking lastly specified style rules for the both of the div that is color blue.
So, I wonder why the ordering of the classes are not maintained?
If this was what I was expecting, would it be an advantage or a disadvantage?
Think about it semantically: A class is just that - some encompassing category to which an element belongs.
If we take the example of a table, some plausible classes might be: "rounded-border" and/or "fixed-width" and/or "blue-background". Suppose a particular table has all of these three classes. If ordering were important, you would require six CSS selectors to target all tables that have these classes instead of just the one.
If the ordering of classes is important in distinguishing between two elements, then create two different classes for them. E.g. one-two and two-one.
Both selectors, .one.two and .two.one, match both div elements here, and the selectors have the same specificity. Thus, by the CSS cascade rules, the latter declaration wins.
The mutual order of the class selectors is irrelevant by definition: the meaning of a class selectors is defined so that the order does not matter.
Moreover, even if it mattered, the HTML attributes class="one two" and class="two one" would still be equivalent, due to the way the the class attribute has been defined in HTML specifications.
What you should do depends on what you wish to accomplish. The question does not specify that. If you need to make the styling of elements depend on the order in which their classes are written in a selector, there is a flaw in the design of markup and styling.
I was reading above discussion and I agree with what BoltClock♦ says and others as well.
but I was refering this Does the order of classes listed on an item affect the CSS?, the use of attribute selectors in CSS where ScottS answered with some
demo 1 demo 2 demo 3
and now I am muddled with whole thing! BoltClock♦ can you please put some more light on the same?
This question already has answers here:
What does a dot before a variable indicate in html?
(4 answers)
Closed 8 years ago.
I am not sure if I understood it correctly. When styling in CSS like this:
body {
}
I'm referring to an element that belongs to HTML. When I write something like this:
.body {
}
I'm referring to a class name given by me. Is this correct?
You may want to have a look at the article on CSS Selectors from MDN, this is also a pretty healthy introductory article on selectors of the type you list, as well as some other important ones.
A non symbol prefixed 'word' denotes an element (body), a 'word' prefixed with a period (.) denotes a 'class' (.body)
Element selectors (called 'type' selectors) only refer to a specific type of element (e.g. body), class selectors can be applied to elements of any type, whereas something like id selectors (a hash preceding a 'word') are unique and can only be applied to a single element (i.e. one id per element, which must not be used elsewhere)
There are many types and combinations of selectors, to get an idea you may also want to read up on CSS specificity
Specificity is the means by which a browser decides which property
values are the most relevant to an element and gets to be applied.
Specificity is only based on the matching rules which are composed of
selectors of different sorts.
Yes.
.body{
}
Would be something like this:
<p class='body'>This is text with a class of body</p>
But can also affect other elements with the class .body.
body{
}
Will affect the body element eg:
<body></body>
You can also use ID's. For example:
#body{
}
And you use this similar to a class. However only 1 ID of the same name per page.
<p id='body'>This is a body tag, but there should only ever be 1 ID per page.</p>
Take a look here for more information.
How can I count the rule specificity in CSS? I know the basic things (1000 for style, 100 for id, 10 for att/class, etc.) However, I still get stuck too many times with simple things, example:
How much would this be?
<div class="wrapper">
<div class="inner"></div>
</div>
.wrapper > div /* ??? */
.inner /* 10 */
The first rule is applied, obviously. But how much is it?
Basically, it's like this:
!important styles always override all other styles, but amongst !important styles, specificity rules do apply
Inline styles get 1000 "specificity" points
IDs get 100 points
(pseudo-)classes and attribute selectors get 10 points
tag selectors get 1 point
If there are selectors with equal specificity, the rule that is defined last on the page will override the other rules.
The universal selector * and inherited styles gets no specificity points.
Also, this site might be useful for you. It explains it a bit further.
After testing these rules for myself, I've noticed that this is not exactly true. The order in which the specificity is applied does still hold true, but going by this test, it is not true that it actually works with this points system like most sites I know claim. What seems to be more accurate is putting the styles in "boxes". It would still use the order of "boxes" I listed above, but instead count each "box", and if there is an equal amount of selectors in that group, check the next one. It would then work like this:
!important styles are in box 1. These styles override all other styles. If there are multiple declarations of the same style that both have the !important rule, then the style in the next highest box will be looked at.
inline styles are in box 2. Inline styles will override all other styles. If there are multiple declarations of inline styles, the one defined last will apply.
ID selectors are in box 3. If there are multiple declarations of the same style, with the same amount of ID selectors, the next highest box will be looked at.
(pseudo-)classes and attribute selectors are in box 4. I think you get the story what happens when there are multiple of the same style with an equal amount of this selector...
tag selectors are in box 5. ...
universal selectors are in box 6. This box behaves a bit differently though, since adding more universal selectors does not increase specificity, as can be seen here, so only the order of definition applies in this box. Styles applied with an universal selector do override inherited styles though.
If no styles have been assigned directly to the element, inherited styles might apply, depending on what style it is.
So basically, if we have a style with 1 id selector at the top of our stylesheet, and below that a style with more than 10 class selectors, the style with the id selector will still apply. The style with the id selector "won the battle" in box 3, so the further boxes are ignored. The specificity calculator Fabrício Matté linked to illustrates really well.
PS: using + or > or ~ or any other operator won't affect specificity at all. These styles have exactly as much specificity (so the latter will apply):
div > span {color:red;}
div span {color:blue;}