More ways of identifying elements

Currently we have only used a simple technique to identify elements, by specifying the element name in the style. However, this has the effect of applying the style to every element of that type throughout the entire document. We may want to identify a particular element, or group of elements though. For example, only the <h1> element at the top of the page, or the first paragraph after every heading, or only paragraphs which are inside a table. Each of these examples are catered for within CSS and more combinations still.

Classes

Any element can be assigned a class name using the 'class' attribute. e.g.

<h1 class="mainheading">My CSS Tutorial</h1>

or

<h2 class="urgent">
<p class="urgent">This is an urgent message</p>

CSS can identify elements by class alone (using the syntax '.classname' or by identifying a class within an element using the syntax 'elementname.classname'.

A style sheet for the above examples could contain the following:

h1.mainheading
  {
    font-family: sans-serif; background-color: #ffff99;
  }
.urgent
  {
    color: red;
  }

The result is that a <h1> tag with class 'mainheading' has a sans-serif font with pale yellow background, and all elements of class 'urgent' have the colour red.

Named elements

Any element may be given a unique identifier by using the 'id' attribute. In this way a style sheet can target a specific element. The syntax for specifying an element this way is '#idname'. This technique is used mainly for styling blocks of XHTML code which are enclosed in a <div> element, although it can be used for any element. For example, the following XHTML fragment:

<div id="header">
  <h1>My web site</h1>
</div>
<div id="menu">
  <ul>
    <li>Home</li>
    <li>Hobbies</li>
  </ul>
</div>  

could be formatted using the following:

#header
  {
    color: red;
  }
#menu
  {
    font-size: smaller;
  }

resulting in all the elements in <div> 'header' being red, and all text in <div> 'menu' having a smaller font size.

Sub-elements

If we want to target elements which are part of another element, e.g. a paragraph in a table cell we do this using the syntax: <element name><space><sub-element-name>. We can use any combination of class, id and specific element name to identify the element we want. For example:

td p
  {
    /* ... styles for paragraphs inside
           a table element */
  }
#header h1
  {
    /* ... styles for all h1 elements inside
           the div named header */
  }
#menu .urgent
  {
    /* ... styles for all elements of class urgent
           inside the div named menu */
  }

We can even put these inside lists of elements. To target all paragraphs inside a table data cell and all lists we could use:

td p, ul, ol, dl
  {
     color: red;
  }
Valid XHTML 1.0! | Valid CSS! | WCAG Approved AA
Page design by: John P Scott - Hosting with: Netcetera