Command Shift

Specificity & Inheritance

Cascading by nature means that rules with higher specificity win. For instance, if the same element is subject to two different rules with the same specificity, the last rule applied is the one that counts. This is not always apparent and sometimes you might wonder why a certain rule you expected to be applied is not.

We should always take into account the Last Rule and the selector Specificity.

Last Rule

If the two selectors are identical, the latter will take precedence. The same applies for rules. If you set the same rules twice, by mistake, in the same selector, the last one will override the first.

Specificity

If one selector is more specific than the others, the more specific rule will take precedence over more general ones. For example:

<h1>Manchester Codes</h1>
<p id="intro">
  Established in 2017, we are the original part-time coding school.
</p>
<p>
  We currently have 2 different courses: Introduction to Programming and
  Software Engineer FastTrack.
</p>
<p></p>
* {
  font-family: Arial, Verdana, sans-serif;
}
 
h1 {
  font-family: "Courier New", monospace;
}
 
p {
  color: black;
}
 
p#intro {
  color: yellow;
}

h1 is more specific than *, so it will take precedence. The same happens for p#intro being more specific than p.

Important

You can add !important after any property value to indicate that it should be considered more important than any other rules an override them. You should use this carefully. In the example below, even though p#intro is more specific, !important will override it.

p {
  color: black !important;
}
 
p#intro {
  color: yellow;
}

Here's a handy specificity calculator.

Inheritance

If you specify font-family or color properties in the body element, they will apply to most child elements. This is because their values are inherited. It basically saves you from having to apply these properties to as many elements, resulting in a much cleaner and simplified stylesheet.

You can also force a lot of properties to inherit values from their parent elements by using inherit as a value:

body {
  padding: 1rem;
}
 
.page {
  padding: inherit;
}

The element with the class page will have the same padding as the body.

When you are setting classes and id's on your elements, bear in mind that classes and id's have different specificity, and if a css rule you have set isn't being applied correctly, check for multiple properties and specificity when debugging.

On this page