Specificity

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.

Related Posts

Beginner’s Guide to Sass

Have you ever wondered what SASS stands for? Or perhaps you already know what it is but haven’t taken the time to study and use it. Whether…

Create a Consistent Cross-Browser Experience

Every browser interprets the HTML specification a little differently. As a result, when identical code is rendered in two different browsers, there are often minor differences in…

What Can CSS Do?

A better question might be: “What can’t CSS do?” CSS can be used to turn an HTML document into a professional, polished design. Here are a few…

Cascading Inheritance

Why are CSS styles called cascading? When multiple rules are written that conflict with each other, the last rule written will be implemented. In this way, styles cascade…

How CSS Works

When writing CSS, there are many times that rules are written that conflict with each other. For example, when styling headers, all of the following rules may…

Best Practices for Preparing Your Markup for Styling

Now that you know how classes, IDs, and element tags can be used as hooks for CSS rulesets, how can you best implement this knowledge to write…