CSS can select HTML elements by their type, class, and ID. CSS classes and IDs have different purposes, which can affect which one you use to style HTML elements.
CSS classes are meant to be reused over many elements. By writing CSS classes, you can style elements in a variety of ways by mixing classes.
For instance, imagine a page with two headlines. One headline needs to be bold and blue, and the other needs to be bold and green. Instead of writing separate CSS rules for each headline that repeat each other’s code, it’s better to write a
.bold CSS rule, a
.green CSS rule, and a
.blue CSS rule. Then you can give one headline the
bold green classes, and the other the
bold blue classes.
While classes are meant to be used many times, an ID is meant to style only one element. As you’ll learn in the next exercise, IDs override the styles of types and classes. Since IDs override these styles, they should be used sparingly and only on elements that need to always appear the same.
To demonstrate using classes on multiple elements, let’s give a few elements the same style.
In index.html, there are four
<h2> elements. Give each of them a class of
Now, let’s give a unique style to a single element using ID.
On line 13 of index.html, there’s an
<h6> element that displays the time the article on the page was published.
Add an id attribute to the
<h6>, and give it a value of
Then, in style.css, create a ruleset targeting the new
heading-background class, and give it a declaration of:
After you press Run, notice how all of the
<h2> elements now have the same style. This
heading-background class can continue to be applied to any element you wish to bestow that amazing style onto.
Finally, in style.css, create another ruleset using the
publish-time ID selector. Add the declaration:
Since ID’s are single-use, this element now has a unique ID that can’t be used again in this document!