CSS Selectors
Selectors are the patterns that decide which HTML elements a CSS rule applies to, from broad element names down to a single unique id.
The three everyday selectors
Most styling is done with three selector types. The element selector uses a tag name and targets every element of that kind. The class selector starts with a dot and targets any element carrying that class. The id selector starts with a hash and targets the one element with that id.
Element, class, and id
<!DOCTYPE html>
<html>
<head>
<style>
p {
color: #444;
}
.note {
color: #00643c;
}
#header {
color: navy;
}
</style>
</head>
<body>
<h2 id="header">Header</h2>
<p>A regular paragraph.</p>
<p class="note">A note paragraph.</p>
</body>
</html>Classes versus ids
A class can be reused on as many elements as you like, which makes it the right choice for styles you want to repeat. An id must be unique on a page, so reserve it for a single, specific element. When in doubt, reach for a class.
Reusing a class
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p class="note">First note</p>
<p class="note">Second note</p>
</body>
</html>Combining selectors
You can chain selectors for more precise targeting. A descendant selector uses a space to match elements nested inside another, so <nav a> styles only the links inside a nav.
Descendant selector
<!DOCTYPE html>
<html>
<head>
<style>
nav a {
text-decoration: none;
color: #00643c;
}
</style>
</head>
<body>
<nav>
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Contact</a>
</nav>
</body>
</html>Exercise: CSS Selectors
Which selector targets every element with class="intro"?