This website may use cookies. More info. That's Fine x
Welcome Login

Class selectors


Css

Think before you class:

Before using a class selector, you should ask yourself:

  1. Is there an existing html element that could be used instead?
  2. Is there a class or id further up the document tree that could be used?

 

 

 

Combining class and type selectors:

If you want to be more specific, you can use class and type selectors together. Any type selectors can be used.

Eg:

div.big { color: blue; }
td.big { color: yellow; }
label.big { color: green}

 

Note: not div .big (ie: a space between type and class selector)

Note2: for: <h2><div class="big">blah</div></h2>

It would be: h2 div.big (where there is a space between parent and child).

 

 

 

Combining multiple classes:

Multiple classes can be applied to one html element:

Eg: to use two rules on one particular element

<p class="big indent">

.big { font-weight: bold; }
.indent { padding-left: 2em; }

 

 

 

Classes should not replace html elements:

It is not advisable to use a class to style html elements to look like other elements.

Some browsers may not recognise style sheets or may have style sheets turned off when they view your page.

Eg: Following is not advised:

/* not advised */
<div class="heading">Heading here</div>

.heading
{
    font-weight: bold;
    font-size: 140%;
    color: #600;
}

 

A preferred method would be:

<h2>Heading here</h2>

h2
{
    font-weight: bold; /* should not really be required */
    font-size: 140%;
    color: #600;
}

 

Or, if you need a specific heading style for one area of your page:

<h2 class="sidenav">Heading here</h2>

h2.sidenav
{
    font-weight: bold;
    font-size: 140%;
    color: #600;
}

 

 

 

Avoid overusing classes:

Class selectors can also be overused.

You could style all the elements within the <div> using one class like this.

<div class="sidenav">
<h2>Site navigation</h2>
<ul>
<li>List item</li>
<li><a href="#">List item</a></li>
<li>List item</li>
</ul>
</div>

 

// With one class in place, you can target any element inside the <div>. The examples below use a combination of class selectors and type selectors. When added together they become descendant selectors:
div.sidenav { blah } /* styles overall div */
div.sidenav h2 { blah } /* styles h2 within the div */
div.sidenav ul { blah } /* styles ul within the div */
div.sidenav li { blah } /* styles li within the div */
div.sidenav li a { blah } /* styles a within li within the div */

 
// So, don't do this:
<div class="sidenav">
<h2 class="sideheading">Site navigation></h2>
<ul class="sidelist">
<li class="sideitem">List item</li>
<li class="sideitem"><a href="#"><span class="sidelink">List item</span></a></li>
<li class="sideitem">List item</li>
</ul>
</div>

Created on: Thursday, March 10, 2011 by Andrew Sin