Getting Started with CSS Rules

In the HTML section, you created an "index.html" file that contained an image and list. This article explains how to add CSS to that document. You will define styles for the <h1>, <p>, and <li> elements. This example uses embedded CSS rules in an external .css file. This method is efficient for styling several documents.

Adding a class

So far we have styled elements based on their HTML element names. This works as long as you want all of the elements of that type in your document to look the same. Most of the time that isn't the case and so you will need to find a way to select a subset of the elements without changing the others. The most common way to do this is to add a class to your HTML element and target that class.

In your HTML document, add a class attribute to the second list item. Your list will now look like this:

<ul>
  <li>Item one</li>
  <li class="special">Item two</li>
  <li>Item <em>three</em></li>
</ul>

In your CSS you can target the class of special by creating a selector that starts with a full stop character. Add the following to your CSS file:

.special {
  color: orange;
  font-weight: bold;
}

Save and refresh to see what the result is.

You can apply the class of special to any element on your page that you want to have the same look as this list item. For example, you might want the <span> in the paragraph to also be orange and bold. Try adding a class of special to it, then reload your page and see what happens.

Sometimes you will see rules with a selector that lists the HTML element selector along with the class:

li.special {
  color: orange;
  font-weight: bold;
}

This syntax means "target any li element that has a class of special". If you were to do this then you would no longer be able to apply the class to a <span> or another element by adding the class to it; you would have to add that element to the list of selectors:

li.special,
span.special {
  color: orange;
  font-weight: bold;
}

As you can imagine, some classes might be applied to many elements and you don't want to have to keep editing your CSS every time something new needs to take on that style. Therefore it is sometimes best to bypass the element and refer to the class, unless you know that you want to create some special rules for one element alone, and perhaps want to make sure they are not applied to other things