CSS Specificity

Id Selector

The CSS ID selector is the most specific type of CSS selector. It is used to select a single element on a web page based on its ID attribute. The ID attribute is a unique identifier for an element, and it can be used to style that element specifically.

To use the CSS ID selector, simply write a hash (#) symbol followed by the ID of the element you want to select. For example, the following CSS rule will set the background color of the element with the ID para to blue:

#para {
  background-color: blue;
}

CSS ID selectors are often used to style elements that are important or unique on a web page, such as the header, footer, or navigation bar. They can also be used to style elements that are dynamically generated, such as modal dialogs or pop-ups.

CSS specificity is a way of determining which CSS rule will be applied to an element when there are multiple rules that apply to that element. The rule with the highest specificity will be applied.

Specificity is calculated by counting the number of elements that a selector matches, the type of selector used, and the order of the selectors.

The following table shows how specificity is calculated:

Selector Type

Weight

ID selector

100

Class selector

10

Element selector

1

Attribute selector

1

The order of the selectors also affects specificity. The first selector in the cascade has the highest specificity, and the last selector has the lowest specificity.

For example, the following two CSS rules have different specificities:

h1 {
  color: red;
}

#myId {
  color: blue;
}

The first rule has a specificity of 101, because it matches all h1 elements and it comes first in the cascade. The second rule has a specificity of 1000, because it matches the element with the id myId and it comes later in the cascade.

Therefore, the second rule will be applied to the element with the id myId, even though the first rule also matches that element.

Task

Change the background color of the paragraph p to gray element using id para. Run the code again to see the changes and experiment with the code to get used to it.

Conclusion

CSS specificity is a complex concept, but it is important to understand how it works in order to write effective CSS. By understanding specificity, you can ensure that your CSS rules are applied in the order that you want them to be applied.

Here are some tips for writing CSS with high specificity:

  • Use ID selectors whenever possible.
  • Use class selectors when you need to apply styles to a group of elements.
  • Use element selectors as a last resort.
  • Order your CSS rules so that the most specific rules come first.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT