Skip to main content

Advanced CSS Selectors

Introduction

CSS selectors are the part of CSS rulesets that determine which elements within the HTML document the rule applies to. They are incredibly powerful, allowing you to select and style elements in a variety of different ways based on their attributes, position in the DOM, and more. In this tutorial, we will learn about some of the more advanced CSS selectors.

Child and Descendant Selectors

Child and descendant selectors provide ways of selecting elements based on their relationship with other elements.

  • Child selectors are denoted by > and select only direct children. For example, div > p selects only p elements that are direct children of a div.

  • Descendant selectors are denoted by a space and select all descendants, not just direct children. For example, div p selects all p elements that are descendants of a div.

Attribute Selectors

Attribute selectors let you select elements based on their attributes. They use the square bracket notation, like a[href] which selects all a elements that have an href attribute.

You can also match specific attribute values:

  • a[href="https://google.com"] matches any a elements where the href attribute is exactly "https://google.com".

  • a[href*="google"] matches any a elements where the href attribute contains "google" anywhere within it.

  • a[href^="https"] matches any a elements where the href attribute starts with "https".

Pseudo-class Selectors

Pseudo-class selectors let you select elements based on their state or position in the DOM.

  • a:hover selects a elements when they are being hovered over.

  • p:first-child selects p elements that are the first child of their parent.

  • p:last-child selects p elements that are the last child of their parent.

  • p:nth-child(2) selects p elements that are the second child of their parent.

Pseudo-element Selectors

Pseudo-element selectors let you style specific parts of an element, like the first letter or line. They are denoted by ::.

  • p::first-letter styles the first letter of every p element.

  • p::first-line styles the first line of every p element.

  • p::before inserts content before every p element.

  • p::after inserts content after every p element.

Conclusion

Advanced CSS selectors give you a lot of power and flexibility when styling your web pages. They can take a bit of practice to get used to, but once you've mastered them, you'll be able to style your pages in sophisticated ways with ease. Happy coding!