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 onlyp
elements that are direct children of adiv
.Descendant selectors are denoted by a space and select all descendants, not just direct children. For example,
div p
selects allp
elements that are descendants of adiv
.
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 anya
elements where thehref
attribute is exactly"https://google.com"
.a[href*="google"]
matches anya
elements where thehref
attribute contains"google"
anywhere within it.a[href^="https"]
matches anya
elements where thehref
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
selectsa
elements when they are being hovered over.p:first-child
selectsp
elements that are the first child of their parent.p:last-child
selectsp
elements that are the last child of their parent.p:nth-child(2)
selectsp
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 everyp
element.p::first-line
styles the first line of everyp
element.p::before
inserts content before everyp
element.p::after
inserts content after everyp
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!