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; }Class Selector
Targets elements with a specific class attribute
.highlight { background: yellow; }ID Selector
Targets a single element with a specific ID
#header { font-size: 2rem; }Universal Selector
Targets all elements on the page
* { margin: 0; padding: 0; }š® 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; }Child Selector (>)
Targets direct children of an element
div > p { color: green; }⨠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