CSS Selectors
CSS selectors are tools for selecting and styling HTML elements. They allow you to apply styles to specific elements based on their tags, classes, IDs, and other characteristics.
Types of CSS Selectors
Basic Selectors
Tag Selector
Class Selector
ID Selector
Universal Selector
Group Selector
Combinator Selectors
- Child selector (
E > F) — selects only direct descendants.
Example:div > pselects paragraphs that are direct children ofdiv. - Adjacent sibling selector (
E + F) — selects the element immediately following the specified one.
Example:h1 + pselects the first paragraph immediately after anh1heading. - General sibling selector (
E ~ F) — selects all elements following the specified one.
Example:h1 ~ pselects all paragraphs following anh1.
Attribute Selectors
[attr]
[attr=value]
[attr*=value]
[attr^=value]
[attr$=value]
Selector Usage Examples
/* Tag selector */
p {
color: red;
}
/* Class selector */
.button {
background-color: blue;
}
/* ID selector */
#header {
font-size: 24px;
}
/* Attribute selector */
input[type="text"] {
border: 1px solid #ccc;
}
Useful Resource
- flukeout.github.io - CSS selector trainer that will help you understand CSS selectors