CSS Selectors
beginnerPart of CSS Fundamentals
Theory
CSS selectors are patterns used to select the HTML elements you want to style. Understanding selectors deeply is essential for writing clean, maintainable CSS.
Basic Selectors
- Element selector: targets all instances of a tag (
h1,p,div) - Class selector: targets elements with a given class, prefixed with
.(.card,.highlight) - ID selector: targets a single element with a specific
id, prefixed with#(#header,#logo) - Universal selector: targets all elements (
*) - Grouping selector: applies same styles to multiple selectors separated by commas (
h1, h2, h3)
Attribute Selectors
Target elements based on attributes or attribute values:
[type="text"] { } /* exact match */
[class~="featured"] { } /* word in space-separated list */
[href^="https"] { } /* starts with */
[src$=".png"] { } /* ends with */
[title*="main"] { } /* contains substring */Pseudo-Classes
Pseudo-classes select elements based on state or position:
:hover,:focus,:active,:visited— user interaction states:first-child,:last-child,:nth-child(n)— position among siblings:not(selector)— negation:empty— elements with no children:checked,:disabled— form element states:root— the document root (<html>)
Combinators
Combinators define relationships between selectors:
div p { } /* descendant — p inside div */
div > p { } /* child — direct child only */
h2 + p { } /* adjacent sibling — p immediately after h2 */
h2 ~ p { } /* general sibling — any p after h2 */Specificity
When multiple selectors target the same element, specificity determines which wins. From lowest to highest:
- Element selectors (
h1,p) — weight 0,0,0,1 - Class/pseudo-class/attribute selectors (
.class,:hover,[attr]) — 0,0,1,0 - ID selectors (
#id) — 0,1,0,0 - Inline styles — 1,0,0,0
The !important declaration overrides everything and should be avoided. When specificity is equal, the rule declared last wins (the cascade).
Use specificity calculators available online to check which selector wins in a conflict. Browsers also show specificity in DevTools.
Practical Examples
Exercises
Style with Advanced Selectors
Create an HTML page with a navigation list, an article with multiple paragraphs, a form, and an image gallery. Use at least one: element selector, class selector, ID selector, attribute selector, pseudo-class (hover, nth-child), descendant combinator, and adjacent sibling combinator.
Expected Output:
A styled page where each selector type produces a visible effect: nth-child stripes rows, attribute selectors style links differently by protocol, hover effects on links, and combinators scope styles to specific sections.