CSS Selectors are the heart of styling in web development. Mastering them will help you write cleaner, smarter, and more maintainable code.

Here are some of the most powerful CSS Selectors tips you should know (and probably use more often).

Resource for developers → http://codewithdhanian.gumroad.com


1. Universal Selector *

Targets every element on the page.

* { margin: 0; padding: 0; box-sizing: border-box; }

2. Element Selector

Targets specific HTML elements.

p { color: #333; }

3. Class Selector .classname

Targets all elements with a specific class.

.button { background: blue; }

4. ID Selector #idname

Targets one unique element.

#hero { padding: 50px; }

5. Descendant Selector (Space)

Targets elements inside another element.

nav ul li { list-style: none; }

6. Child Selector >

Targets only direct children.

div > p { color: green; }

7. Adjacent Sibling +

Targets the next immediate sibling.

h2 + p { margin-top: 10px; }

8. General Sibling ~

Targets all following siblings.

h2 ~ p { color: gray; }

9. Attribute Selector

Targets elements with specific attributes.

input[type="text"] { border: 1px solid #000; }

10. Starts With Attribute ^=

a[href^="https"] { color: green; }

11. Ends With Attribute $=

img[src$=".png"] { border-radius: 10px; }

12. Contains Attribute *=

a[href*="github"] { color: purple; }

13. Pseudo-Class :hover

Adds styles when an element is hovered.

button:hover { background: black; }

14. First Child :first-child

Targets the first child element.

li:first-child { font-weight: bold; }

15. Last Child :last-child

li:last-child { color: red; }

16. nth-child()

Targets elements by position.

tr:nth-child(even) { background: #f9f9f9; }

17. Not Selector :not()

Excludes elements.

p:not(.special) { color: gray; }

18. Empty Selector :empty

Targets elements with no content.

div:empty { display: none; }

19. Pseudo-Elements ::before & ::after

Inserts content before or after.

h1::after { content: "🔥"; }

20. Grouping Selectors

Apply styles to multiple selectors.

h1, h2, h3 { font-family: sans-serif; }

Final Tip: Combine Selectors for Power

ul.menu > li:first-child a:hover { color: gold; }

Use selectors wisely for clean, scalable, and maintainable CSS.


Conclusion

Mastering CSS Selectors gives you total control over your website styling. The better you understand them, the cleaner and faster your CSS workflow becomes.

Keep learning. Keep building.

→ More developer resources & ebooks: http://codewithdhanian.gumroad.com