Because we don’t want to style all our HTML elements at once, we need to be able to target a subset of these HTML elements.
CSS selectors define which elements we want our styling to be applied to.
Generic tag selectors
Targeting generic HTML tags is easy: just use the tag name.
There’s a direct connection between the name of the HTML tag and the CSS selector used.
Classes
Considering we probably don’t want to style all paragraphs or all titles identically, we need to differentiate them.
Of all HTML attributes, the class
attribute is the most important for CSS. It allows us to define a group of HTML elements that we can target specifically. Just put a dot .
in front of the class name you want to use:
On one side, there is the HTML class
attribute with the value date
. It must match the name of the CSS class.
You can use any name for your CSS class, as long as it doesn’t start with a number.
The .date
class selector will target all HTML elements that have the class="date"
attribute. So, the following HTML elements will all be styled:
Saturday Feb 21
The event will be on Saturday.
Bear in mind that the tag name is irrelevant. Only the class
HTML attribute is.
IDs
You can also use the id
attribute in your HTML, and target it with a hash #
in your CSS:
ID are similar to Classes, as they rely upon an HTML attribute.
Example
HTML | Possible CSS selectors | What it means |
---|---|---|
|
p |
Every <p> |
|
div .global div.global |
Every <div> Every elements with class=”global” Every <div> with class=”global”
|
|
#menu ul#menu
|
The only element with id=”menu” The only <ul> with id=”menu”
|
|
li ol li .dico li
|
Every <li> Every <li> with an <ol> as ancestor Every <li> with a class="dico" element as ancestor
|
Combining selectors
Let’s reuse our previous example where we want our dates to be red:
Saturday Feb 21
The event will be on Saturday.
What if we want our dates that are in em
elements to blue instead? We can add the following CSS rule:
The em.date
combines:
- a tag selector
em
- a class selector
.date
It will only apply to <em class="date"></em>
HTML elements. It won’t affect other .date
or em
.
Hierarchy selectors
A space in a selector defines a ancestor/descendant relationship. Let’s say we want the links in our header to be in red:
This can be read from right to left as: “Select all a
elements that are within a header
element”. This will prevent all other links (that aren’t in the header) from being affected.
Pseudo-class selectors
HTML elements can have different states. The most common case is when you hover over a link. It’s possible in CSS to apply a different style when such an event occurs.
Pseudo-class selectors are attached to usual selectors and start with a colon :
: