CSSLesson 2 of 10Jump to practice
CSS selectors
Target elements by name, by class or by id, and learn when to use each one.
The selector is the part of a rule that decides which elements it styles. Here are the three you will use most.
| Selector | Example | Selects |
|---|---|---|
| Element | p |
Every <p> |
| Class | .warning |
Every element with class="warning" |
| ID | #signup |
The one element with id="signup" |
Classes
A class lets you style some elements of a type but not others. Add a class attribute in HTML, then select it in CSS with a dot.
<!DOCTYPE html>
<html>
<head>
<style>
p { color: #333; }
.warning {
color: #9a3412;
background: #ffedd5;
padding: 8px 12px;
}
</style>
</head>
<body>
<p>A normal paragraph.</p>
<p class="warning">This paragraph has the warning class.</p>
<p>Another normal paragraph.</p>
</body>
</html>An element can have more than one class. Separate them with spaces: class="warning big".
IDs
An id must be unique on the page. Select it with #.
#signup {
border: 2px solid teal;
}
Grouping
To give several selectors the same style, separate them with commas:
<!DOCTYPE html>
<html>
<head>
<style>
h1, h2, h3 {
font-family: sans-serif;
color: navy;
}
</style>
</head>
<body>
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
</body>
</html>Practice
Check what you just learned. Fill in the missing code, then answer the quiz.
Exercise 1Solved
Select every element with the class
price.{ font-weight: bold; }Class selectors start with a dot.
Exercise 2Solved
Select the one element with the id
menu.{ background: navy; }ID selectors start with a hash sign.
Exercise 3Solved
Give the paragraph the class
notein the HTML.<p ="note">Remember to save your work.</p>
Finish the practice to complete this lesson.
Sign in to keep your progress on any device.