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 SelectorClass SelectorID SelectorUniversal SelectorGroup Selector
Combinator Selectors
- Child selector (
E > F) — selects only direct descendants.
Example: div > p selects paragraphs that are direct children of div.
- Adjacent sibling selector (
E + F) — selects the element immediately following the specified one.
Example: h1 + p selects the first paragraph immediately after an h1 heading.
- General sibling selector (
E ~ F) — selects all elements following the specified one.
Example: h1 ~ p selects all paragraphs following an h1.
Attribute Selectors
[attr][attr=value][attr*=value][attr^=value][attr$=value]
Selector Usage Examples
css
/* 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
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.