Logo
TUTORIAL

CSS Selectors: The Complete Reference

Think of CSS Selectors as a search engine for your HTML. They allow you to find specific elements and apply visual rules to them. Without a solid understanding of selectors, your CSS will become a repetitive mess.

Level 1: Simple Selectors

Basic Targeting

These are the fundamental ways to pick elements based on their name, class, or unique identity.

Selector Syntax Example & Use Case
Universal * * { margin: 0; } - Resets all elements.
Element tag p { line-height: 1.5; } - Styles all paragraphs.
Class .name .btn { border: none; } - Styles reusable components.
ID #name #navbar { position: fixed; } - Styles one unique element.
Level 2: Combinators

Relationship Selectors

Combinators explain the relationship between two selectors. They are used when you want to style an element only if it resides within a specific parent or follows another element.

/* 1. Descendant Selector (Space) */ /* Targets all <p> tags inside <div> */ div p { color: blue; } /* 2. Child Selector (>) */ /* Targets only <p> tags that are direct children of <div> */ div > p { font-weight: bold; } /* 3. Adjacent Sibling Selector (+) */ /* Targets the first <p> immediately following a <div> */ div + p { margin-top: 20px; }
Level 3: Attributes

Attribute Selectors

These allow you to style elements based on the presence or value of an HTML attribute (like type, href, or target).

/* Targets all inputs with type="text" */ input[type="text"] { border: 2px solid #ccc; } /* Targets all links that open in a new tab */ a[target="_blank"] { color: red; } /* Targets images where 'alt' contains the word "logo" */ img[alt*="logo"] { width: 100px; }
Level 4: States

Pseudo Selectors

Pseudo-classes style an element's state (hover, focus), while pseudo-elements style a specific part of an element (like the first letter).

Type Selector Result
Pseudo-Class :hover Styles when user hovers mouse.
Pseudo-Class :nth-child(2n) Styles every even row (useful for tables).
Pseudo-Element ::before Inserts content before the element.
Pseudo-Element ::placeholder Styles the hint text inside inputs.
The Rule of Specificity: Not all selectors are equal. An ID (#) is stronger than a Class (.), and a Class is stronger than an Element. If you apply different colors to the same tag using both, the strongest one wins!

IDE Settings

X