Class and ID
Goal
- ⚡Learn how to use
class
andid
for css selector.
Class and ID
In addition to HTML tag like <h1>
, you can use class
and id
as css selector.
And this is more common way to apply CSS.
Let's edit css-test1.html
file like below.
css-test1.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="css-test1.css" />
</head>
<body>
<h1>Here is a title.</h1>
<h2>Here is a subtitle.</h2>
<ul>
<li class="drink" id="coffee">Coffee</li>
<li class="drink tea">Tea</li>
<li class="drink">Milk</li>
</ul>
</body>
</html>
css-test1.css
h1 {
color: white;
background-color: navy;
}
ul {
background-color: #ffff00;
}
.drink {
color: red;
}
#coffee {
text-decoration: underline;
}
.tea {
font-weight: bold;
}
The output is like below...
id
and a class
?
Difference between an
id
s are unique
- Each element can have only one
id
- Each page can have only one element with that
id
class
es are NOT unique
- You can use the same
class
on multiple elements.- You can use multiple
class
es on the same element.
https://stackoverflow.com/a/12889416
So...
❌ Bad
<ul>
<li class="drink" id="coffee">Coffee</li>
<li class="drink" id="coffee">Coffee 2</li>
<li class="drink tea">Tea</li>
<li class="drink">Milk</li>
</ul>
✅ Good
<ul>
<li class="drink" id="coffee-1">Coffee 1</li>
<li class="drink" id="coffee-2">Coffee 2</li>
<li class="drink tea">Tea</li>
<li class="drink">Milk</li>
</ul>