CodingBison

In addition to selecting HTML elements by their tag, CSS provides another way to get hold of elements -- by using CSS class. CSS allows multiple elements to have the same class name. When specifying a class as a selector, the convention is to add a dot character (".") before the CSS class name.

Let us now look at an example that highlights selection of elements using the CSS class. This example embeds a CSS file ("class_selector.css") that contains the CSS rules.

The HTML content in this example (provided below) is fairly simple. It has a paragraph element and an ordered list with child list elements. Among these HTML elements, we use two CSS classes: "blue" and "green".

 <!doctype html>
 <html>
 <head>
     <title> Learning CSS: CSS Class Selectors </title>
     <link type="text/css" rel="stylesheet" href="class_selector.css">
 </head>

 <body>
 <p class="blue">
 The Mesozoic Era was the age of dinosaurs. This Era lasted 180 million
 years and consisted of the following three periods. The evolution of dinosaurs
 started during the Triassic period, they became dominant animals during
 the Jurassic period, and became extinct at the end of the Cretaceous period.
 </p>
 <ol>
     <li class="blue"> Triassic period </li>
     <li class="green"> Jurassic period </li>
     <li class="blue"> Cretaceous period </li>
 </ol>
 </body>
 </html>

In our example, we use CSS to select elements using their class. The syntax to do that is straightforward -- we specify the name of the class and as per the CSS syntax, add a dot operator ("." ) before the name of the class. The CSS (provided below) adds rules for both CSS classes: "blue" and "green".

 /* This rule adds style to the "blue" class elements. */ 
 .blue {
     font-family: Helvetica, Verdana, sans-serif;
     font-weight: bold;
     color: blue;
 }

 /* This rule adds style to the "green" class elements. */
 .green {
     font-family: Helvetica, Verdana, sans-serif;
     font-weight: bold;
     color: green;
 }

If we were to load the above HTML page, the output (see below) would illustrate that the <li> element belonging to the "green" class has a green color. On the other hand, the two <li> elements and the <p> element that belong to the "blue" class have blue color. In addition, all of the elements have a bold font-weight and have a font that is selected from the list: Helvetica, Verdana, sans-serif. This demonstrates that we can keep different elements in different classes and assign design as per different classes. Here is the output:



Figure: Using CSS class Selector

Please note that if we want to specify a design to all classes, then one option would be to use the "*" selector. As a matter of fact, this selector not only selects all classes on a page, but all other elements as well.





comments powered by Disqus