CSS selectors target HTML elements so you can apply styles. There are several types of selectors.
Select all elements of a type:
p { color: blue; }
h1 { font-size: 32px; }Select elements with a specific class:
.highlight { background-color: yellow; }
.error { color: red; }<p class="highlight">Important text</p>Select a unique element by ID:
#header { background-color: navy; }<div id="header">My Site</div>Select by attributes:
input[type="text"] { border: 1px solid gray; }
a[href^="https"] { color: green; } (space) — Descendant selector> — Child selector+ — Adjacent sibling~ — General siblingdiv > p { color: blue; } /* p directly inside div */
h1 + p { margin-top: 0; } /* p immediately after h1 */CSS applies rules based on specificity:
1. Inline styles (highest)
2. IDs
3. Classes and attributes
4. Elements (lowest)
CSS selectors target HTML elements so you can apply styles. There are several types of selectors.
Select all elements of a type:
p { color: blue; }
h1 { font-size: 32px; }Select elements with a specific class:
.highlight { background-color: yellow; }
.error { color: red; }<p class="highlight">Important text</p>Select a unique element by ID:
#header { background-color: navy; }<div id="header">My Site</div>Select by attributes:
input[type="text"] { border: 1px solid gray; }
a[href^="https"] { color: green; } (space) — Descendant selector> — Child selector+ — Adjacent sibling~ — General siblingdiv > p { color: blue; } /* p directly inside div */
h1 + p { margin-top: 0; } /* p immediately after h1 */CSS applies rules based on specificity:
1. Inline styles (highest)
2. IDs
3. Classes and attributes
4. Elements (lowest)