CSS CSS Tutorial CSS Advanced CSS Responsive Web Design(RWD) CSS Grid CSS Properties Sass Tutorial Sass Functions



CSS Specificity

CSS specificity is a way to determine which CSS rule will be applied to an element when multiple rules are targeting the same element. It is important to understand CSS specificity in order to write efficient and effective CSS code.

The specificity of a CSS selector is determined by the number of ID selectors, class selectors, and element selectors in the selector. The more specific a selector is, the higher its specificity.

For example, consider the following CSS code:


#header {
  background-color: red;
}

.header {
  background-color: blue;
}

div {
  background-color: green;
}

If we have the following HTML code:


<div id="header" class="header"></div>

The background color of the div element will be red, because the ID selector has a higher specificity than the class selector or the element selector.

It is important to note that inline styles have a higher specificity than any other selector. So if we have the following HTML code:


<div id="header" class="header" style="background-color: yellow"></div>

The background color of the div element will be yellow, because the inline style has the highest specificity.

Here are some examples of CSS specificity:


/* ID selector */
#header {
  color: red;
}

/* Class selector */
.header {
  color: blue;
}

/* Element selector */
div {
  color: green;
}

/* ID selector + element selector */
#header div {
  color: purple;
}

/* Class selector + element selector */
.header div {
  color: orange;
}

/* ID selector + class selector */
#header.header {
  color: pink;
}

In the above examples, the specificity of the selectors increases from top to bottom.

It is important to write CSS code that is specific enough to target the desired elements, but not so specific that it becomes difficult to maintain. In general, it is best to avoid using ID selectors in CSS, as they can lead to specificity wars and make it difficult to override styles.

By understanding CSS specificity, you can write more efficient and effective CSS code that targets the desired elements and is easy to maintain.

References

Activity