CSS Selectors

CSS selectors are used to “find” (or select) the HTML elements you want to style.

element Selector

The element selector selects HTML elements based on the element name.

1
2
3
4
p {
text-align: center;
color: red;
}

The CSS id Selector

To select an element with a specific id, write a hash (#) character, followed by the id of the element.

1
2
3
4
#para1 {
text-align: center;
color: red;
}

The CSS class Selector

To select elements with a specific class, write a period (.) character, followed by the class name.

You can also specify that only specific HTML elements should be affected by a class.

1
2
3
4
5
6
7
8
.center {
text-align: center;
color: red;
}
p.center {
text-align: center;
color: red;
}
  • HTML elements can also refer to more than one class.
1
<p class="center large">This paragraph refers to two classes.</p>

The CSS Universal Selector

The universal selector (*) selects all HTML elements on the page.

1
2
3
4
* {
text-align: center;
color: blue;
}

The CSS Grouping Selector

The grouping selector selects all the HTML elements with the same style definitions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
h1 {
text-align: center;
color: red;
}

h2 {
text-align: center;
color: red;
}

p {
text-align: center;
color: red;
}
h1, h2, p {
text-align: center;
color: red;
}