The Class Attribute

The class attribute is used to identify the style class for an element. A good practice is to name classes according to their function or action rather than the appearance on the page.

For example, with this tutorial I have classes in the tutorials style sheet for the HTML code examples and the CSS code examples giving each a different text color. Any CSS code will have a blue color and any HTML code will have a brown color.

The CSS class .css {color:#00a;}
The HTML class .html {color:#900;}

The HTML code would be:

<p class="css">.css {color:#00a;}</p>
<p class="html">An example of html code</p>

Now I could have used blue as the CSS selector and brown as the HTML selector. The problem, if in the future I decide to go with green for CSS. having it named blue wouldn't make any sense if the text color is green.

Assigning classes to specific elements

In the above examples, the CSS & HTML classes may be applied to any body element. There is no HTML element assigned to them.

Say you want to have a class that can only be used on the p(paragraph) element. Example let's set up two classes, we will call them true and false. True will be green and false will be red.

.true {color:green;}
.false {color:red;}

As they are now these classes can be assigned to any body element. To have them only work with the p element we modify the CSS by placing a p in front of the class selector.

p.true {color:green;}
p.false {color:red;}

Now if we attempt to use these classes on any other element the class will be overlooked because it has the HTML element specific p.

In the editor below the two p elements will be in their respective colors while the h elements will not have the red and green colors.

View it first and then remove the p from the css and view it again.