The second rule that determines which rules are applied to each HTML element is the rule of specificity.
CSS rules with more specific selectors will overrule CSS rules with less specific selectors regardless of which occurs first. As we discussed, the three most common selectors are element tags, classes, and ids.
- The least specific type of selector is the element level selector.
- When a class is used as a selector it will overrule CSS rules written with the element tag as the selector.
- When an ID is used as a selector it will overrule the CSS rules written with element or class selectors.
Another factor that influences specificity is the location where the CSS styles are written. Styles written inline with the style
attribute overrule styles written in an internal or external stylesheet.
Another way to increase the specificity of a selector is to use a series of elements, classes, and IDs to pinpoint the element you want to address. For example, if you want to pinpoint unordered list items on a list with the class “example-list” contained with a div
with the id “example-div” you could use the following selector to create a selector with a high level of specificity.
div#example-div > ul.example-list > li {styles here}
While this is one way to create a very specific selector, it is recommended to limit the use of these sorts of selectors since they do take more time to process than simpler selectors.
Once you understand how inheritance and specificity work you will be able to pinpoint elements on a web page with a high degree of accuracy.