Little Web Hut
(Cascading Style Sheets) CSS 2.1 Reference

CSS Class Selector

 

What is a CSS Class Selector?

  • The class selector specifies elements that have class attributes equal to a specific value. This selector uses period (.) notation where the value of the class attribute immediately follows the period. If the period is not immediately preceded by a selector then the style will be applied to all elements with matching class attribute values. In the following example, the text-align property will be set to center for both the <h1> and <p> elements since both of their class attributes are equal to tst1.
CSS Example:
  .tst1 {text-align: center;}
  <h1 class="tst1">Style applies to this element.</h1>
  <p class="tst1">Style applies to this element.</p>
Test It HTML StyleTest It XHTML StyleTest It HTML5 Style

  • If the period is immediately preceded by a selector then the style will only be applied to matching elements that also have matching class attribute values. In the following example, the text-align property will be set to center for all <h1> elements that also have class attribute values of tst1. In this case, the first <h1> element is the only element that the style will be applied to. The style is NOT applied to the second <h1> element and the <p> element.
CSS Example:
  h1.tst1 {text-align: center;}
  <h1 class="tst1">Style applies to this element.</h1>
  <h1>Style does not apply to this element.</h1>
  <p class="tst1">Style does not apply to this element.</p>
Test It HTML StyleTest It XHTML StyleTest It HTML5 Style

  • The class attribute value for elements can be a space-separated list. The class selector can specify multiple values in the list by preceding each value with a period. In the following example, the text-align property will be set to center for all <h1> elements that have both tst1 and tst2 included in the class attribute space-separated list. In this case, the first two <h1> elements are the only elements that the style will be applied to. The style is NOT applied to the third <h1> element.
CSS Example:
  h1.tst1.tst2 {text-align: center;}
  <h1 class="tst1 tst2">Style applies to this element.</h1>
  <h1 class="tst1 tst2 tst3">Style applies to this element.</h1>
  <h1 class="tst1 tst3">Style does not apply to this element.</h1>
Test It HTML StyleTest It XHTML StyleTest It HTML5 Style