DEV Community

Cover image for 7 Advanced CSS Selectors You Should Know
Mainul Hasan
Mainul Hasan

Posted on • Originally published at Medium

7 Advanced CSS Selectors You Should Know

CSS is indispensable when we talk about web design and development. Basic selectors like classes (.) and IDs (#) might be familiar, but some advanced selectors can make your code efficient and elegant. Let’s explore 7 of these lesser-known yet incredibly powerful selectors.

1. Child Selector (>)

parent > child

This selector targets direct child elements of a specified parent, ignoring deeper nested elements.

ul > li { 
    color: blue; 
}
Enter fullscreen mode Exit fullscreen mode

This will style only the direct li children of ul, leaving nested li elements unaffected. Perfect for when you need precision and want to ensure styles don’t unintentionally cascade to nested elements. All modern browsers and as far back as IE7 support this feature.

2. Adjacent Sibling Selector (+)

element1 + element2

If you’ve ever needed to target an element immediately following another, the Adjacent Sibling Selector (+) is your go-to.

h2 + p {
    margin-top: 10px;
}
Enter fullscreen mode Exit fullscreen mode

This provides a 10px top margin to any paragraph immediately following an h2. Especially handy for managing spacing after specific elements.

3. Attribute Selector ([attr=value])

element[attr=value]

Matches elements based on their attribute and their value.

input[type="text"] {
    border: 1px solid gray;
}
Enter fullscreen mode Exit fullscreen mode

Styles all input fields of type text with a gray border. This is useful for styling specific form elements or elements with unique data attributes.

4. Pseudo-classes (:pseudo-class)

element:pseudo-class

This selector focuses on elements by their state, position, or other unique traits rather than their structure.

a:hover {
    color: red;
}
Enter fullscreen mode Exit fullscreen mode

Changes link color to red when hovered over. Enhance interactivity (like hover and focus states) and select elements based on position (like :first-child).

5. Not Selector (:not())

element:not(selector)

The Not Selector :not() excludes specific elements from being styled.

p:not(.special) {
    font-weight: normal;
}
Enter fullscreen mode Exit fullscreen mode

Styles all paragraphs without the class “special” to have a normal font-weight. This allows you to apply broad styles while exempting particular cases.

6. Universal Selector (*)

*

The Universal Selector * is a wildcard that matches every element on a webpage.

* {
    box-sizing: border-box;
}
Enter fullscreen mode Exit fullscreen mode

Assigns the box-sizing property to all elements, making layout calculations more intuitive. Useful for global styles or CSS resets.

7. Grouping Selector (,)

selector1, selector2, …

Last but not least, the Grouping Selector lets you apply the same styles to multiple elements.

h1, h2, h3 {
    font-family: 'Arial', sans-serif;
}
Enter fullscreen mode Exit fullscreen mode

Sets a consistent font across the three header levels. A time-saving approach when various elements share a set of styles.

Conclusion

CSS offers an incredible depth and flexibility that becomes more apparent as you explore its advanced selectors. You might not often use these selectors, but if you know how to use them, you can simplify your code and improve your style.

🖥️ Before you head back to your coding zone, consider these quick actions:

❤️ & 🦄 Show some love or sprinkle some unicorn magic on this article
💬 Curious or have insights? Drop your thoughts in the comments
🔄 Spread the word among our developer community

Your feedback is invaluable. It empowers me to craft even better tech content.

🌟 Thank you for being such a fantastic supporter! Every like, comment, and share shines a light on our tech community.

Feel free to connect with me on Twitter or LinkedIn.

Top comments (21)

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️ • Edited

Nice post, but I'm not sure if "advanced" is really the right word here; some of these are definitely less common, but some others have been found in every beginner CSS tutorial for the last few decades.

Some more selectors that I'd consider "advanced" would for example be :nth-child, :is(), :has(), etc.

Collapse
 
mainulspace profile image
Mainul Hasan

Thank you for taking the time to read and provide feedback on the article. I appreciate your insights!

You make a valid point about some of these selectors being part of beginner tutorials. My intention with the term "advanced" was to highlight selectors that go beyond the absolute basics like class and ID selectors, especially for readers who might just be diving a little deeper into CSS. However, I understand that "advanced" might feel like a stretch for some developers, especially those who have been in the field for a while.

I'm glad you brought up :is(), :has(), and :nth-child() (I believe you might've meant this instead of :next-child). Those are indeed fantastic selectors that offer more depth and targeting capabilities. I'll consider covering them in a follow-up piece, diving into even more nuanced aspects of CSS selectors.

Thank you again for your valuable feedback. Continuous learning and sharing are what make our developer community so vibrant, and I appreciate your contribution to that!

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

Yes, you're absolutely right about :nth-child() 😅 (I edited my comment to correct that)

Making a follow-up post with another set of selectors sounds like a nice idea 👍 Depending on how advanced you wanna make it, there's also a lot of potential in combining all those selectors, specially now that :is() and :has() are a thing.

Thread Thread
 
mainulspace profile image
Mainul Hasan

Thank you for the correction and the great suggestion! I absolutely agree — the power of CSS selectors, especially when combined, can achieve some truly intricate and effective stylings. :is() and :has() indeed open up a world of possibilities. Thanks again for being such an engaged reader! 👩‍💻🌟

Collapse
 
gktim profile image
gkTim

Well done!

There are some more selectors if someone is interested, have a look at:

Collapse
 
mainulspace profile image
Mainul Hasan

Thanks for sharing these additional resources! 🙌 Mozilla's documentation is indeed a gold mine for developers. I'll definitely check them out and encourage others to do the same. Cheers! 🚀

Collapse
 
mardeg profile image
Mardeg

Great refresher! I sometimes have to go back to CSS code I did to remember how I managed to, for example, get the list style images to work as ticked checkboxes on all steps preceding the current focused one in a how-to guide. Turns out I used the ~ relative selector backwards!

Collapse
 
mainulspace profile image
Mainul Hasan

Thank you! Ah, the joys of revisiting past code and discovering the clever tricks we once used. The ~ general sibling selector can be tricky but powerful when used correctly. Uncovering those "aha!" moments in our work is always fun. Keep up the creative coding! 👩‍💻🌟

Collapse
 
thomasbnt profile image
Thomas Bnt

Great post 💥✨

Collapse
 
mainulspace profile image
Mainul Hasan

Thank you so much! 💙 I'm glad you found it helpful. Do you have a favorite CSS selector or any tips to share? Always love learning from the community!

Collapse
 
thomasbnt profile image
Thomas Bnt • Edited

Love using :not() !

:not - CSS : Feuilles de style en cascade | MDN

La pseudo-classe de négation, :not(), est une notation fonctionnelle qui prend un sélecteur comme argument. Elle permet de cibler les éléments qui ne sont pas représentés par cet argument. Le sélecteur passé en argument ne doit pas contenir d'autre sélecteur de négation et ne doit pas cibler de pseudo-élément.

favicon developer.mozilla.org
Thread Thread
 
mainulspace profile image
Mainul Hasan

Ah, the :not() selector is indeed powerful! It's a great way to exclude specific elements and can make stylesheets so much cleaner. Thanks for sharing the MDN link and description. Happy coding! 🚀

Collapse
 
roniardynt profile image
Ron

thanks, great tips

Collapse
 
mainulspace profile image
Mainul Hasan

Thank you for the kind words! I'm glad you found the tips useful. If you have any other CSS-related questions or topics you'd like covered, let me know. Happy coding! 🚀

Collapse
 
zippcodder profile image
Deon Rich

Nice article, good for those who are starting out 👍.

Collapse
 
mainulspace profile image
Mainul Hasan

Thank you so much! I'm glad you found it useful. Happy coding! 👩‍💻🚀

Collapse
 
sreno77 profile image
Scott Reno

Good info. Thanks for sharing!

Collapse
 
mainulspace profile image
Mainul Hasan

You're welcome! Glad you found it helpful. 😊

Collapse
 
sumonbarai profile image
sumon barai

nice post

Collapse
 
mainulspace profile image
Mainul Hasan

Thank you so much! I'm glad you found it useful. Happy coding! 👩‍💻🚀

Collapse
 
chris48hemsworth profile image
Chris Hemsworth

🎨💡 Uncover the magic of CSS wizardry with "7 Advanced CSS Selectors You Should Know"! 🚀✨ This blog is a treasure trove for anyone passionate about web design and development. Elevate your styling game by delving into the secrets of these advanced selectors, carefully curated to empower your designs and create visually stunning websites.

Mastering these advanced CSS selectors is like adding a touch of finesse to your coding palette, allowing you to sculpt your web projects with precision and elegance. From sibling combinators to attribute selectors, this blog unveils the secrets that will set your CSS skills apart. Enhance your understanding, streamline your coding process, and bring your visions to life in the digital realm.

Don't miss out on this enlightening read – level up your CSS expertise and transform the way you craft web experiences. Get ready to shape the future of web design! 🌟🔥
However, You can find more information about Advanced CSS selector from the website given.