Pin Me

Leveraging CSS Styles

written by: Carmelo Carbonara•edited by: Linda Richter•updated: 10/12/2008

An example of how to set styles with various style tags using CSS selectors.

  • slide 1 of 3

    Introduction

    The Cascading Style Sheet 2 standard (CSS2) is a great way of pre-defining styles for rendering HTML elements in the client's browser. Going one step further, CSS2 selectors allow the style definitions to be extended to descendants and child nodes.This minimizes repetitious class and style attribute assignments. The example below uses a div element wrapped around a ul and subsequent li elements.

    The ul element is a descendant of the div element and the li element is a descendant of the ul element. The sample code below shows how to set the style for the li elements using CSS selector syntax. This eliminates the need to set the class or style attributes for each li element in the list.

  • slide 2 of 3

    CSS Selector Syntax

    To see how this works, paste the code views into your editor.

    Code view: paste into the head section

    <style type="text/css">

    <!--

    body { font-family: "Microsoft Sans Serif", sans-serif;font-size: 12px;font-weight: normal;}

    /* below is the syntax for any element with id="sampleDiv " */

    #sampleDiv {border:solid 1px lightgrey;margin-top:30px;margin-bottom:30px;}

    /* below is the syntax for applying the hover pseudo class (essentially mouseover) for any element with id="sampleDiv " having ul descendant that have li descendants */

    #sampleDiv ul li:hover {background:cyan;cursor:pointer;}

    /* below is the syntax for any div element with class="sampleDiv2" */

    div.sampleDiv2 {border:solid 1px red;margin-top:30px;margin-bottom:30px;}

    /* below is the syntax for applying the hover pseudo class to any div element with class="sampleDiv2" having ul descendants that have li descendants */

    div.sampleDiv2 ul li:hover {background:lightyellow;cursor:pointer;}

    -->

    </style>

    Code view paste this into the document body section

    <div id="sampleDiv">

    <ul>

    <li>List item 1</li>

    <li>List item 2</li>

    <li>List item 3</li>

    <li>List item 4</li>

    </div>

    <div class="sampleDiv2">

    <ul>

    <li>List item 1</li>

    <li>List item 2</li>

    <li>List item 3</li>

    <li>List item 4</li>

    </ul>

    </div>

  • slide 3 of 3

    Conclusion

    As you can see, CSS selectors are a powerful way to apply formatting given various constructs. It saves a lot of time and trouble when developing web sites. CSS2 is widely implemented in the recent browser versions as well as legacy versions. Some references on CSS2 and selector syntax is provided below

    W3 Schools CSS2 Reference

    W3 Org Selector Syntax