CSS Selectors: Targeting HTML Elements
A CSS selector lets you apply one or more style declarations to specific elements on a web page. Let’s explore the different types of selectors and how they work.
1. Basic Selectors
To style an element, you use its tag name as a selector. For example, to make all <p> elements yellow:
Code Block Loading...
Every HTML tag—like <div>, <span>, <img>—can be targeted this way. If multiple elements match the selector, all of them will be styled.
Class and ID Selectors
HTML elements often use the class and id attributes for styling:
- Class (
.): Can be reused across multiple elements. - ID (
#): Must be unique within the document.
Example using a class:
Code Block Loading...
Example using an ID:
Code Block Loading...
2. Combining Selectors
2.1 Targeting an Element with a Class or ID
You can combine a tag with a class or ID for more specificity.
Class example:
Code Block Loading...
ID example:
Code Block Loading...
This helps when you want to style only a specific type of element with a class or ID.
2.2 Targeting Multiple Classes
You can target elements with multiple classes by chaining them with dots:
Code Block Loading...
2.3 Combining Class and ID
You can also combine a class and an ID:
Code Block Loading...
3. Grouping Selectors
To apply the same style to multiple selectors, separate them with commas:
Code Block Loading...
You can format grouped selectors across multiple lines for clarity.
4. Tree-Based Selectors
Selectors can follow the document tree structure to target nested elements.
Descendant Selector
Targets elements nested inside another:
Code Block Loading...
This applies to any <span> inside a <p>, even if deeply nested.
Child Selector (>)
Targets only direct children:
Code Block Loading...
Only the first <span> gets styled.
Adjacent Sibling Selector (+)
Styles an element that immediately follows another:
Code Block Loading...
The <span> is styled only if it directly follows a <p>.
What’s Next?
You’ve now seen how to use:
- Tag selectors
- Class and ID selectors
- Combined and grouped selectors
- Tree-based and sibling selectors
Up next: Attribute selectors, Pseudo-class selectors, Pseudo-element selectors in coming tutorials.