CSS Selectors

Master the art of targeting HTML elements with precision. CSS selectors are your key to styling web pages effectively!

šŸŽÆ What You'll Learn

Basic Selectors

Element, Class, ID, and Universal selectors

Combinator Selectors

Descendant, Child, and Sibling selectors

Pseudo Selectors

:hover, :nth-child, and more advanced selectors

šŸŽØ Basic Selectors

Element Selector

Targets all elements of a specific type

p { color: blue; }
Live Demo

Class Selector

Targets elements with a specific class attribute

.highlight { background: yellow; }
Live Demo

ID Selector

Targets a single element with a specific ID

#header { font-size: 2rem; }
Live Demo

Universal Selector

Targets all elements on the page

* { margin: 0; padding: 0; }
Live Demo

šŸŽ® Interactive Selector Playground

Try CSS Selectors

Write your own CSS and see immediate results!

Quick Examples to Try:

Live Preview

Welcome

This is a paragraph

Special paragraph

Nested paragraph

šŸ”— Combinator Selectors

Descendant Selector (space)

Targets elements that are descendants of another element

div p { color: red; }
Live Demo

Child Selector (>)

Targets direct children of an element

div > p { color: green; }
Live Demo

✨ Pseudo-class Selectors

:hover

Styles when mouse hovers over element

button:hover { background: blue; }

:focus

Styles when element receives focus

input:focus { border-color: blue; }

:active

Styles when element is being activated

button:active { transform: scale(0.98); }

:nth-child()

Selects elements based on their position

li:nth-child(odd) { background: gray; }

:first-child

Selects the first child element

p:first-child { font-size: larger; }

:last-child

Selects the last child element

p:last-child { margin-bottom: 0; }

:not()

Excludes elements from selection

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

:disabled

Selects disabled form elements

input:disabled { opacity: 0.5; }

:checked

Selects checked radio/checkbox

input:checked { accent-color: green; }

šŸ† Best Practices

āœ… Do's

  • āœ“Use classes for reusable styles
  • āœ“Keep specificity low when possible
  • āœ“Use semantic HTML with appropriate selectors
  • āœ“Use descendant selectors for scoped styling

āŒ Don'ts

  • āœ—Don't overuse !important
  • āœ—Avoid overly specific selectors
  • āœ—Don't use IDs for styling
  • āœ—Avoid universal selector for performance

Ready to Continue Learning?

Ā© 2024 WebDevLearn. Making web development accessible for everyone.

VIDO - Learn Web Development