Skip to content

The Hierarchy of CSS Selectors: Combining Selectors for Specificity

Posted on:April 10, 2023 at 11:00 AM

CSS selectors allow you to apply styles to specific HTML elements. One of the most important concepts to understand when working with selectors is the hierarchy of selectors. Selectors can be combined in a variety of ways to create more specific styles.

One of the most common selectors is the descendant selector. This selector allows you to select elements that are children of a particular element. For example, if you have a list of items within a div, you can use the descendant selector to select the list items within that div:

div ul li {
  /* Styles for list items within the div */
}

Another useful selector is the child selector. This selector allows you to select elements that are direct children of a particular element. For example, if you have a div with a list inside of it, you can use the child selector to select the list:

div > ul {
  /* Styles for the list inside the div */
}

The adjacent sibling selector is another useful selector. This selector allows you to select elements that come immediately after another element. For example, if you have a heading followed by a paragraph, you can use the adjacent sibling selector to style the paragraph:

h2 + p {
  /* Styles for the paragraph that comes immediately after the heading */
}

By combining these selectors, you can create more specific styles for your HTML elements. For example, you can use the descendant selector and the child selector together to select only the list items that are inside a particular div:

div.special ul > li {
  /* Styles for list items within the special div */
}

Conclusion

Understanding the hierarchy of selectors is an essential part of working with CSS. By learning how to use these selectors effectively, you can create more specific and targeted styles for your HTML pages.

What’s next?

In the coming article, we will be covering pseudo-classes and pseudo-elements in CSS. Don’t forget to follow and share this with your friends that are just starting their web development journey.