CSS selector specificity guide.

CSS is the style sheet language used for designing websites. It helps to make a website look more attractive and organized. But, in order to achieve the desired layout and design, it is important to understand how CSS selectors work and how they prioritize styles. This is where CSS selector specificity comes into play.

In simple words, CSS selector specificity refers to the way in which the browser determines which CSS style to apply to an HTML element. When there are multiple styles applied to the same element, the browser uses selector specificity to determine which style takes priority.

Here are some practical examples to help you undestand the concept of selector specificity:

Example 1:

Conside the following CSS and HTML:

CSS:

p {
    color: blue;
}

p.highlight {
    color: red;
}

HTML:

<p class="highlight">This is a paragraph.</p>

In this example, both styles are applied to the same <p> element, but the style with the class selector .highlight has a higher specificity and therefore takes precedence over the style with the type selector p. This means that the text in the paragraph will be displayed in red.

Example 2:

Consider the following CSS and HTML:

CSS:

p {
    color: blue;
}

#container p {
    color: green;
}

HTML:

<div id="container">
  <p>This is a paragraph.</p>
</div>

In this example, both styles are applied to the same <p> element, but the style with the ID selector #container p has a higher specificity and therefore takes precedence over the style with the type selector p. This means that the text in the paragraph will be displayed in green.

Example 3:

Consider the following CSS and HTML:

CSS:

p {
    color: blue;
}

body p {
    color: green;
}

HTML:

<body>
  <p>This is a paragraph.</p>
</body>

In this example, both styles are applied to the same <p> element, but the style with the tag selector body p has a higher specificity and therefore takes precedence over the style with the type selector p. This means that the text in the paragraph will be displayed in green.

Conclusion:

In conclusion, CSS selector specificity is an imporant concept to understand when working with CSS. It determines which style takes precedence when multiple styles are applied to the same element. The higher the specificity of a selector, the more likely it is that its style will be applied.

I hope this post has helped you to understand the concept of selector specificity. For more information on CSS, desigh and web development, be sure to check our our other blog posts.

For more deep information on Specificity:

Access: mdn web docs