Learn CSS 2.5: Classes and IDs

11/29/18 - How to style only some instances of an element.

Last time

Last time we learned:

Very useful features.

Professional web developers usually end up using a lot of <div>s, since they are the simplest tag whose only default rule is display: block; (what does that mean? We'll learn later.) So how do they make them all look different?

Enter classes and IDs. Classes allow a developer to categorize elements and style each category. Meanwhile, IDs give each element a unique name which can be referenced in a stylesheet. Giving an element a class or id is as simple as adding a class= or id= attribute. Classes are referred to as .classname and IDs as #id

Take for example, the following code:

<div class=myfirstclass></div>
<div class=myfirstclass id=myfirstid></div>
<div class=mysecondclass id=mysecondid></div>
<div class=mysecondclass id=mythirdid></div>
<div></div>

There are five tags here. A CSS rule for .myfirstclass would affect the first two. #myfirstid would affect only the second tag. Meanwhile, div would affect all of them. So, with:

<!DOCTYPE html>
<html>
<head>
<meta name=viewport content="width=device-width, initial-scale=1" />
<style>
.myfirstclass {
    color: red;
}
.mysecondclass {
    color: blue;
}
#myfirstid {
    background-color: green;
}
#mysecondid {
    background-color: orange;
}
#mythirdid {
    background-color: purple;
}
</style>
</head>
<body>
<div class=myfirstclass>I used to find Slashdot delightful,</div>
<div class=myfirstclass id=myfirstid>But my feelings of late are more spiteful,</div>
<div class=mysecondclass id=mysecondid>My comments sarcastic</div>
<div class=mysecondclass id=mythirdid>The iconoclastic</div>
<div>Keep modding to plus five (insightful).</div>
</body>
</html>

The first two lines will have red text, the second two will have blue text, and the lines in order will have white, green, orange, purple, and white backgrounds, despite all of them being DIVs. Limerick credit: XKCD