CSS selectors are used to target specific elements in your HTML document. They allow you to apply styles to elements based on their tags, classes, IDs, attributes, and more.
Basic Selectors
- Element selectors: Target elements based on their tag name (e.g., p, h1, div).
- Class selectors: Target elements with a specific class attribute (e.g., .container, .item).
- ID selectors: Target elements with a unique ID attribute (e.g., #header).
- Attribute selectors: Target elements based on their attributes (e.g., [href], [data-foo=”bar”]).
Beyond the Basics
In addition to these basic selectors, CSS offers several other powerful techniques for targeting elements:
1. Descendant Combinator
- Targets elements that are descendants of another element.
Example:
CSS
.container p {
color: blue;
}
2. Child Combinator
- Targets elements that are direct children of another element.
Example:
CSS
.container > p {
color: blue;
}
3. Adjacent Sibling Combinator
- Targets elements that are adjacent siblings of another element.
Example:
CSS
p + span {
color: red;
}
4. General Sibling Combinator
- Targets elements that are siblings of another element, regardless of their order.
Example:
CSS
p ~ span {
color: red;
}
5. Pseudo-classes
- Target elements based on their state or position.
Example:
CSS
a:hover {
color: blue;
}
input:focus {
border: 2px solid #ccc;
}
6. Pseudo-elements
- Create generated content within elements.
Example:
CSS
p::before {
content: “>”
}
7. Grouping Selectors
- Combine multiple selectors using commas to target multiple elements at once.
Example:
CSS
h1, h2, h3 {
font-weight: bold;
}
By mastering these advanced selector techniques, you can create more targeted and efficient stylesheets for your responsive web designs.