I usually trace my CSS stylesheet by using the Chrome web browser.
I can see that some of my styles are being ignored by the inspection window of Chrome - the style is struck out with a black line.
I cannot see why it is being ignored. Usually, I follow all the styles using my eyes to see why it is ignored.
Can I know the structure (inheritance) information by Chrome or by other method?
In Short, Specificity
From CSS Specificity: Things You Should Know:
Specificity determines, which CSS rule is applied by the browsers.
Specificity is usually the reason why your CSS-rules don't apply to some elements, although you think they should.
Every selector has its place in the specificity hierarchy.
If two selectors apply to the same element, the one with higher specificity wins.
There are four distinct categories which define the specificity level of a given selector: inline styles, IDs, classes+attributes and elements.
You can understand specificity if you love Star Wars: CSS Specificity Wars.
You can understand specificity if you love poker: CSS Specificity for Poker Players.
When selectors have an equal specificity value, the latest rule is the one that counts.
When selectors have an unequal specificity value, the more specific rule is the one that counts.
Rules with more specific selectors have a greater specificity.
The last rule defined overrides any previous, conflicting rules.
The embedded style sheet has a greater specificity than other rules.
ID selectors have a higher specificity than attribute selectors.
You should always try to use IDs to increase the specificity.
A class selector beats any number of element selectors.
The universal selector and inherited selectors have a specificity of 0, 0, 0, 0.
You can calculate CSS specificity with CSS Specificity Calculator.
For example
If you had a p with class a, what would you predict it's color would be based on the following rules:
p.a { color: red; }
.a { color: blue; }
If you said blue, you'd be wrong!
As Alochi pointed out, if you're looking for more of a Tree View of the styles hit by a particular element, in the Chrome Developer Tools, go to the computed tab and expand the property you're interested in. You'll get a full list of all the other rules that apply to that element with a link to each. From what you know about specificity and cascading, it should be clearer why the "winner" was chosen.
I generaly find Firebug for Firefox, a little more featrured for debugging CSS.
Selecing an element and viewing the computed tab will show where a particular style is coming from. That will then help with the question of "why".
Most web developers are aware of the cascading nature of style shees and how that works: Inline > Page > Sheet. That is which ever is declare last is applied. What not as many developers are aware of is specifity.
http://css-tricks.com/specifics-on-css-specificity/
http://www.htmldog.com/guides/css/intermediate/specificity/
In a nut shell the more specific the selector, the higher priority.
E.g #anID.aClass will overide p.aClass will overide .aClass
Kyles' answer has more on specificty
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).
I have constructed a mock-up of a hierarchical menu system, where the main menu (#moduleMenu1) has a sub-menu (#moduleMenu2), and they both share a CSS class. When I use ID selectors on the menus, all is well (http://jsfiddle.net/stamminator/pwnuymd2/1). However, when I switch to using a class selector, which would be much more elegant (especially if I add a third hierarchy to the menus), the selectors are being overwritten (http://jsfiddle.net/stamminator/pwnuymd2/).
I suppose I can use !important on every property in my styles, but assuming I'll need to have a page which overwrites those styles on an as-needed basis at some point, this isn't a great solution either. Is there a third option besides id selectors or !important that is available?
I'm not sure if this is related, but I've noticed a second problem as well. When I have the HTML files open locally and do a selector in Chrome's JavaScript console on their shared class, I would expect to get back both elements. Instead, I only get back one.
//what I typed into the console:
$(".moduleMenu");
//my result:
<div id="moduleMenu1" class="moduleMenu">
<div>
Proposal
Browse
Financial
Documents
</div>
</div>
//where's #moduleMenu2? They both have the same CSS class
Here is a link so you can download the files and run it in your own debugger if you'd like: https://onedrive.live.com/redir?resid=9F7FCE5CCA52BABF!33812&authkey=!ANi0Ivf0BbmVbGk&ithint=file%2czip.
The JavaScript console issue is a non-issue I suppose, but I figured I'd mention it in case it's related. Any help I can get in getting my CSS working properly would be much appreciated!
ID selectors are of higher importance than class selectors. You should almost never use IDs in CSS. Change your ID selectors to class selectors (even if they're unique) and be happy.
<div id="moduleMenu1" class="moduleMenu moduleMenu1">
Demo
Of course, some of your listed selectors can now be combined.
Demo 2
As mentioned by isherwood, ID selectors take priority over class selectors. This is due to CSS specificity, which is the way CSS determines which rules are applied to an element.
The simplest way to explain CSS specificity is:
!important > inline > ID > class > element > universal & inherited
For a slightly more in-depth explanation, CSS specificity is stored as four separate integers. When no styles are applied to an element (or only universal and inherited rules are applied), the values for that element are 0,0,0,0.
The first value represents inline styles
The second value represents ID style rules
The third value represents class or attribute style rules
The fourth value represents tag style rules
1,0,0,0 overrides 0,1,0,0: an inline style will always override an ID style rule. Likewise, an ID will always override a class. However, 0,1,1,0 overrides 0,1,0,0, so a class and an ID in a rule will override the ID rule.
With the exception of some older browsers that roll over values after 255, there is no number of classes that can override an ID: the only way to override an ID style rule is with an ID, inline styles, or the !important flag.
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;}
i am trying to injecting font styles for web pages on a web browser.
to change every element of the page.
* {
font-size: 100%;
font-family: Arial!important;
}
in this question almost done the trick but this style get overridden. i want to prevent those overrides too. use of javascript to the solution is also ok.
If it got overridden, make sure it is the last thing in your style sheet (or the last stylesheet you include). The "Cascading" in CSS means that last definition wins.
Add !important to the font-size declaration, too:
* {
font-size: 100% !important;
font-family: Arial !important;
}
If you are using this in a user style sheet (as the words “trying to injecting font styles for web pages on a web browser” suggest), then your rule cannot be overridden.
If, on the other hand, this is just part of an author style sheet, then it can be overridden by a user style sheet, and there is nothing you can do about it. It will not be overridden by a browser default style sheet, as they don’t use !important. With respect to other author style sheets, the cascade rules imply that you cannot be overridden except by a rule that uses !important, too.
In a fight between author style sheet rules that both have !important, the more specific wins, with specificity exactly defined by CSS specifications. Between equally specific settings, the one that comes latest wins.
The selector * has the lowest possible specificity 0,0,0,0. For any selector, you can always construct another selector with a higher specificity. However, a CSS rule inside a style attribute for an element is considered as having the highest specificity.
So if you know which other CSS rules will be used, you can beat them by adding selectors with a higher specificity in your selector list.