Why does an earlier CSS rule override a later rule? - css

In my stylesheet, .four-across li defines width: 174px; at line 8806. Below that rule at line 9603, .no-search-results defines width: auto;. However, the 174px rule is overriding an element with .no-search-results. Why would that be?

You should read about CSS specificity.
.four-across li is more specific than .no-search-results, so it have higher importance level.
Specificity is calculated by counting various components of your css
and expressing them in a form (a,b,c,d). This will be clearer with an
example, but first the components.
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)
by Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade
Document order matters only when given specificity is exactly the same. In you example first selector is (0,0,1,1) and second is (0,0,1,0), so the first one overrides the second one, no matter how are they ordered within CSS document.

Read:
Reviewing CSS Style Priority Level
Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade
In this case it's because a class and an element type are more specific than just a class, and it's favored over the order.

Two reasons:
The last rule scanned has precedence over those scanned previously, all else being equal.
The more specific the rule is (two specifiers as opposed to one) the higher the precedence.

Related

Overriding combined css classes

There are numerous questions about the order of loading CSS files and overriding classes, but after reading them I still have something I can't figure out.
There are two CSS files:
<link rel="stylesheet" href="standard.css" type="text/css">
<link rel="stylesheet" href="override.css" type="text/css">
loaded in this order (I checked that).
The HTML looks like this:
<div class="div_D1 ov_D1">
<div class="div_D2 ov_D2">
<div class="div_D3 ov_D3">
blablah
</div>
</div>
</div>
Standard.css contains:
.div_D1{
background: white;
}
.div_D2{
height: 10px;
}
.div_D1 .div_D3{
padding-left: 20px;
}
Override.css contains:
.ov_D1{
background: red;
}
.ov_D2{
height: 50px;
}
.ov_D3{
padding-left: 0px;
}
.ov_D1 and .ov_D2 are applied correctly: the background of .div_D1 is red, the height of .div_D2 is 50px.
.ov_D3 on the other hand does not behave as I expected. If I look at the order the rules are applied, the browser first applies .ov_D3, and then .div_D1 .div_D3, leaving me with an unwanted padding of 20px.
If however I change the class selector in Override.css to
.div_D1 .ov_D3 it does remove the padding.
Also changing the css to
.ov_D3{
padding-left: 0px; !important
}
does the trick. So there are solutions, I only can't understand why with a single selector the order of loading is respected, and with multiple selectors it is not.
This is called specificity of a Selectors. From the book Beginning CSS: Cascading Style Sheets for Web Design, Third Edition by Ian Pouncey and Richard York:
In addition to style sheet precedence, an order of precedence exists for the selectors contained in each style sheet.
This precedence is determined by how specific the selector is.
For example, an ID selector is the most specific,
and the universal selector is the most general. Between these, the
specificity of a selector is calculated using the following formula:
Count 1 if the styles are applied from the (X)HTML style attribute, and 0 otherwise; this becomes variable a.
Count the number of ID attributes in the selector; the sum is variable b.
Count the number of attributes, pseudo-classes, and class names in a selector; the sum is variable c.
Count the number of element names in the selector; this is variable d.
Ignore pseudo-elements.
Now take the four values and put them together in groups of four.
For Example:
Selector : div.someclass.someother
Selector Type : Element Name + Class Name + Class Name
specificity:
0,0,2,1, (a = 0, b = 0,
c = 2, d = 1)
In CSS, there are rules for specificity (quoted from MDN):
The following list of selectors is by increasing specificity:
Universal selectors
Type selectors
Class selectors
Attributes selectors
Pseudo-classes
ID selectors
Inline style
Since you have added specificity to your Selector you weren't able to override by normal CSS class selector.
So your Code
.div_D1 .div_D3is more specific than.div_D3and less specific than.div_D3.ov_D3.
JS Fiddle
As per MDN CSS selectors have rules called 'Specificity' which determine their order of precedence. The more specific a rule is, the greater it's priority regardless of position within a/some stylesheet(s).
A rule such as .class-1 .class-3 has a specificity (it's more specific) higher than .class-3 and takes precedence, as such the less-specific rule cannot override it without the use of !important which negates all other specificity rules. Using the higher specificity rule only takes place with conflicting styles, however.
So, you have set the rule:
.div_D1 .div_D3 { }
The above rule is more specific than:
.ov_D3 { }
Even though they target the same element the rule with the higher specificity takes precedence. You can fix this in your JS Fiddle by prepending the appropriate class structure as defined above.
So, .ov_D3 becomes either:
.div_D1 .ov_D3
or
.ov_D1 .ov_D3
Example here: JS Fiddle

why is the order writen in css making a difference to my design

In my CSS I have the following:
.myDiv{
float:left;
width:100px;
height:100px;
}
.yellow{
background:#faf8c7;
}
.lightGrey{
background:#f8f8f8;
}
In my HTML
<div class="myDiv lightGrey yellow"></div>
This should display the div as the yellow colour but instead it is lightGrey.
If I change the order of the .yellow and .lightGrey in my CSS (not HTML) then the div becomes yellow...why is this?
Surely it should be the order that the classes are written in the HTML that determines whether the div is yellow or grey. The order of the CSS should be irrelevant.
surely it should be the order that the classes are written in the html that determines whether the div is yellow or grey
It's how the cascade was defined:
Find all declarations that apply to the element and property in question, for the target media type. Declarations apply if the associated selector matches the element in question and the target medium matches the media list on all #media rules containing the declaration and on all links on the path through which the style sheet was reached.
Sort according to importance (normal or important) and origin (author, user, or user agent). In ascending order of precedence:
user agent declarations
user normal declarations
author normal declarations
author important declarations
user important declarations
Sort rules with the same importance and origin by specificity of selector: more specific selectors will override more general ones. Pseudo-elements and pseudo-classes are counted as normal elements and classes, respectively.
Finally, sort by order specified: if two declarations have the same weight, origin and specificity, the latter specified wins. Declarations in imported style sheets are considered to be before any declarations in the style sheet itself.
#4 is the part you're struggling with, the declarations have identical specificity, and therefore the latter one is winning.
Cascading Style Sheet.
That means that style that appears later in the stylesheet will overwrite style that appeared earlier in the sheet.
order in your html code of each class myDiv lightGrey yellow is not important at all, it's like you say : I bought 3 colors, but we don't know what is the first or the last you bought
since all rules have the same specificity, the last one (for the meaning of Cascade) specified in the CSS wins. In other words, no matter you re-arrange your classes in the markup, with the given style your background is always lightgray.
Surely it should be the order that the classes are written in the HTML that determines whether the div is yellow or grey. The order of the CSS should be irrelevant.
for the above explanation it's the opposite

Why does bootstrap accept form styling for only one highly specific css classes?

I have a jsbin with a table of inputs, using bootstrap. What confuses me is that the style with
input.someClass {
background-color: blue;
}
is applied, as expected, but
.anotherClass {
background-color: green;
}
is not applied to my input elements. What is the reason for this? For reference, check out http://jsbin.com/enaris/3/edit
What is the reason for this?
It's simply a matter of specificity - the first selector has a type selector attached to the class name whereas the second selector only has a single class. The second selector is therefore more specific and takes precedence.
This is migrated from another answer of mine, it may help:
You can think of specificity as four numbers, starting with (0,0,0,0):
!important rules always take precedence, only another !important rule
can override a previous one (its an accessibility feature of CSS,
designed to override the UA stylesheet)
The universal selector (*) has a specificity of 0
Combinators like + and ~ also have no specificity
Inline styles have the highest specificity (other than !important)
and count as the first number (1,0,0,0)
ID's (#test) count as the second number in the above set (0,1,0,0)
Classes, pseudo-classes and attribute selectors are the third number
(0,0,1,0)
Type selectors and psuedo-elements (e.g. - <p> & ::after) take place of the
fourth number, and are the least specific
Remember that if two rules have the same specificity and specify the
same property the latter in the stylesheet will win
Based on the above, the first selector has a specifictiy of (0,0,1,1) while the second only has (0,0,1,0)
CSS rules are applied from least specific to most specific.
You have:
Least Specific More Specific Most specific
.anotherClass input[type=...] (bootstrap) input.someClass
So, in your example b-cell is more specific than bootstrap styles and a-cell is less.
You can force a-cell to take precedence with !important (but use !important with caution, as it might become a debugging hell):
.a-cell {
background-color: green !important;

Efficient Algorithm To Compare Specificity Of CSS Rules

I was wondering what an efficient algorithm would be in the following scenario:
Given a parsed set of css rules, eg.
p.pStyle{margin-bottom:20px;font-family:Arial;}
p{font-family:Verdana;}
p.anotherPStyle{margin-bottom:10px;}
from a css stylesheet, it is possible that several rule sets apply to a given element (say a <p class="pStyle anotherPStyle">hello</p> in my document).
I need to determine what rules in the stylesheet apply to a given element firstly (so here that is p, pStyle and anotherPStyle), and then create a Comparator that is able to sort the applicable rules by specificity (from most-specific to most-general). NOTE: I already have designed an algorithm to apply the rules once sorted so you needn't solve that problem efficiently.
I've been toying with several ideas, namely one that involves determining the level in the DOM tree that a given rule is specific to....Though I'm not sure if this is the correct way to go?
How does the browser engine do this efficiently? I'm looking to replicate it in Java, but am comfortable with many other languages so any code you can offer is most appreciated.
Thanks
That is determined by specificity. In this case, since they are both equally specific, the declaration that comes last in the file, wins.
Specificity Calculation
Specificity is calculated by ranking the different parts of the selector.
Ranked from most specific to least:
Style attribute - If the rule is found in a style attribute, this rank gets 1.
ID - For each ID found in the selector, this rank gets an additional 1.
Classes, Pseudo-Classes, Attribute selectors - For each one found in the selector, this rank gets an additional 1.
Elements - For each element found in the selector, this rank gets an additional 1.
Where rank n > rank n+1, regardless of how many points each rank has.
Example
ul#nav li.active a
The points are:
0 - Not a style attribute.
1 - 1 ID found.
1 - 1 Classname found.
3 - 3 Elements found.
Therefore, each property in that selector has a specificity value of [0,0,1,1,3] (We'll get to that extra zero in a minute). That value is more specific than any selector, as long as it might be, without an ID, for example.
Comparison algorithm:
Go from left to right on the ranks.
Compare the ranks on both selectors.
The rank with the higher amount of point, wins.
If the ranks are equal, continue right to the next (less specific) rank.
If all ranks are equal, the one which comes later in the CSS document, wins.
More important notes:
The universal selector (*) has no specificity value (0,0,0,0) Pseudo-elements (e.g. :first-line) get 0,0,0,1 unlike their
pseudo-class brethren which get 0,0,1,0
The pseudo-class :not() adds no specificity by itself, only what's inside it's parentheses.
The !important directive can be applied on a single declaration, and adds a point to a "0th" rank, which is more specific than anything
else. So in the example above, adding !important on any rule will
bump the specificity value for that rule only to [1,0,1,1,2],
granting it an instant win over any other rules without !important.
Extra Reference
See this great article on the subject
How to determine which styles go to what element
The way the browser does it, is to go over the selector from right to left, and filtering elements out of the DOM as they go.
Going back to the previous example:
ul#nav li.active a
The browser does the following:
Take an a element.
Now check if it has an ancestor that is a li element with an .active class (this is through the descendant combinator: ancestor descendant).
Now check if it has a higher ancestor that is a ul with an ID of #nav (again, the descendant combinator is used).
If all these conditions are met for a certain element, then the styles are applied to it.
You can read it:
Select any a element
with an ancestor with a class of .active, which is also a li,
which in turn has an ancestor with an ID of #nav, which is also a ul.
You'll need to have a fully function and complete DOM tree to be able to successfully determine which element has what CSS styles.

CSS class repetition to increase specificity

According to the CSS docs:
http://www.w3.org/TR/CSS21/cascade.html#specificity
Specificity is defined by (amongst other things) the number of attributes and pseudo-classes in the selector.
So, my question is, is it possible to increase specificity by repeating the same classname over and over again?
For instance:
would
.qtxt.qtxt.qtxt.qtxt.qtxt
{
}
have a higher specificity than
.qtxt.lalgn
{
}
or
.lalgn .qtxt//(space added to create child selector)
{
}
?
Yes, it is possible and intentionally so. While this is not mentioned in the CSS2 spec, it is explicitly mentioned in the Selectors 3 spec:
Note: Repeated occurrances [sic] of the same simple selector are allowed and do increase specificity.
Therefore browsers must increase the specificity when encountering repeated simple selectors, as long as the selector is valid and applicable. This not only applies to repeated classes, but also applies to repeated IDs, attributes and pseudo-classes.
Given your code, .qtxt.qtxt.qtxt.qtxt.qtxt will have the highest specificity. The other two selectors are equally specific; combinators have no bearing in specificity calculations at all:
/* 5 classes -> specificity = 0-5-0 */
.qtxt.qtxt.qtxt.qtxt.qtxt
/* 2 classes -> specificity = 0-2-0 */
.qtxt.lalgn
/* 2 classes -> specificity = 0-2-0 */
.lalgn .qtxt
Also, the space in your last selector is the descendant combinator; the child combinator is >.
.qtxt.qtxt.qtxt would have the highest specificity...
http://jsfiddle.net/nXBTp/1/
However, this is only the case if you repeat the class name more times that any other selector, for example:
http://jsfiddle.net/nXBTp/2/
You shouldn't need to hack specificity like this... if you need to force a value, use !important.

Resources