Generic tag selectors

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:

.date{color:red;}

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:

<pclass="date"> Saturday Feb 21</p><p> The event will be on <emclass="date">Saturday</em>.</p>

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:

#tagline{color:orange;}

<h1id="tagline">This heading will be orange.</h1>

ID are similar to Classes, as they rely upon an HTML attribute.

Example

HTML

Possible CSS selectors

What it means

<p></p>

p

Every <p>

<div class="global"></div>

div.globaldiv.global

Every <div>
Every elements with class=”global”
Every <div> with class=”global”

<ul id="menu">

#menuul#menu

The only element with id=”menu”
The only <ul> with id=”menu”

<ol class="dico">
<li>Un cobaye</li>
<li>Des cobaux</li>
</ol>

liol 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:

.date{color:red;}

<pclass="date"> Saturday Feb 21</p><p> The event will be on <emclass="date">Saturday</em>.</p>

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:

em.date{color:blue;}

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:

headera{color: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::