CS 100 (Learn)CS 100 (Web)Module 08


CSS :: Classes

Let's continue expanding our example of styling the <cite> element.

What if we want to have different colours for references to movies, television shows and books.

It might seem that a style sheet will not work, as you can only specify one style per element type in the sheet.

The solution to this problem is to introduce style classes. The following example illustrates how classes can be used:

CSS
.movie { color: green; }
.tvshow { color: red; }
.book { color: blue; }
HTML
Maisie Williams was on <cite class="tvshow">Meet the Actor</cite>
and discussed her biggest mistake when playing Arya Stark on <cite class="tvshow">Game of Thrones</cite>.
In the novel <cite class="book">A Game of Thrones</cite>,
it is revealed that Arya is <em>left-handed</em>, and she decided to play her left-handed on the show.
She expressed how refreshing it was to be right-handed again when filming her upcoming movie <cite class="movie">The New Mutants</cite>.
web browser

Maisie Williams was on Meet the Actor and discussed her biggest mistake when playing Arya Stark on Game of Thrones. In the novel A Game of Thrones, it is revealed that Arya is left-handed, and she decided to play her left-handed on the show. She expressed how refreshing it was to be right-handed again when filming her upcoming movie The New Mutants.

 

Any element (tag) in HTML can be given a class using the class attribute:

  <tagname class="classname">

This has no affect on the HTML, but allows us to apply style to that instance of the tag.

We will discuss syntax shortly, but it is important to note that the class name in the CSS is preceded by a period (.classname) but the period does not appear in the class attribute (class="classname").

The class names you choose should be meaningful and descriptive (stick to letters and hyphens such as my-class-name). In the above example, it would be unhelpful (bad) to have one of the classes be red-text. Not only do you have to keep track of which type of <cite> was to be red, if you change your mind later and wish to use a different colour, the class name would just be confusing.