The CSS Class Selector

How do we specify an class selector?

  • Class selectors let you assign styles in a way that is independent of document elements. These selectors can be used on their own or in conjunction with type selector.
  • You use class selectors in your web pages by giving the class attribute for the appropriate html elements the name of the class selector.
    .className {color:red; font-size:12px; line-height:15px;}
    /* For a class selector that is independent of document elements
    you only start with a dot and then the name of the class.*/
    elementName.className {color:red; font-size:12px; line-height:15px;}
    /* If you would like the class selector to be
    related to an html element you need to provide the name of html element,
    followed by a dot and then the name of the class selector.*/
    A class selector example:
    <html>
      <head>
        <style type="text/css">
          p { color: green;} /* this is a type selector */
          p.warning {font-size: 16pt; color: blue; }
          .myclass { color: red;}
        </style>
      </head>
      <body>
        <h1 class='myclass' >The header has now a red color</h1>
        <p>This paragraph has no class selector, but a type selector</p>
        <div class='myclass'>
          Text inside the div tag is red.
          <p class='warning'>paragraph inside div element is now blue and 16 pt.</p>
         </div>
      </body>
    </html>
    Of course, you can create a descendant selector or a child selector that is a mix of a class selector and a type selector.
    div p.myclass {color:red; font-size:12px;}
    With this CSS rule in effect, any HTML code containing an p element with attribute class='myclass' inside an div element on the web page is automatically rendered in 12-pixel font-size type and colored red.
    div>p.myclass {color:red; font-size:12px;}
    With this CSS rule in effect, any HTML code containing an p element with attribute class='myclass' as direct child element inside an div element on the web page is automatically rendered in 12-pixel font-size type and colored red.

© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.