CSS selectors
Consider the following HTML.
<div class="summary">
<h1 id="emphasised">Make this text red</h1>
<h2>Not this text</h2>
</div>
<div>
<h1>Not this text</h1>
</div>
What CSS would we have to write to make the first <h1>
element turn red, but not the second one?
Tag selectors
We can target all content inside a HTML tag of a certain type with a CSS statement like:
h1 {
color: red;
}
However, that won't work in this situation, because both <h1>
elements will turn red.
Class selectors
We can also target HTML classes, such as the class summary
on the first <div>
, by putting a full stop before the selector.
.summary {
color: red;
}
However, that still won't work, because both the <h1>
and <h2>
will turn red.
Chaining selectors
We can write chained selectors like this.
.summary h1 {
color: red;
}
This CSS statement will do what we need. Because we used a chained selector, we are targeting all <h1>
elements inside anything with a class of summary
.
ID selectors
There is one other solution which will work. We can target the ID of the <h1>
element we want to turn red by putting a hash (#
) before the ID name.
#emphasised {
color: red;
}
Part of Building webpages
- Your first webpage
- Introducing HTML
- HTML attributes
- Classes and IDs
- Introducing CSS
- CSS selectors
- CSS specificity
- Creating layouts
- Responsive design
- Get confident with HTML and CSS
- Turn your prototypes into webpagesP