Watkins Web 1

Part 5: Advanced Selectors

Writing efficient CSS means being smart about your selectors. Here are some of the most useful techniques.

Select a series of HTML elements using comma-separated selectors

/* Make the headers, lists, and paragraphs 
the same font size */
h1, h2, h3, p, ul, ol {
	font-size: 10px;
	}

Use descendent selectors to apply different styling to elements based on their container

For example, let’s remove bullets from our navigation list but make them circles on our content’s bulleted lists.

/* Select unordered lists inside the NAVIGATION div */
div#nav ul {list-style:none;}
/* Select unordered lists inside the MAIN div */
div#main ul {list-style-type:circle;}

Create a “current” class to highlight a particular navigation item on a page

/* Make the current navigation item black 
instead of the default blue */
#nav li.current a {color:black;}

Just make sure to move the class to the corresponding list item on each page. The home page should look contain code that looks like this:

<ul id="nav">
	<li class="current"><a href="home.html">Home</a></li>
	<li><a href="about.html">About</a></li>
	<li><a href="contact.html">Contact</a></li>
</ul>

while the about page should look like this:

<ul id="nav">
	<li><a href="home.html">Home</a></li>
	<li class="current"><a href="about.html">About</a></li>
	<li><a href="contact.html">Contact</a></li>
</ul>

Highlight the current navigation item without changing your HTML

You can even achieve this same effect without the special class: instead, apply a page-identifying id to your body tag, give each navigation item its own id, and then use descendent selectors to apply the style selectively. Your HTML would look something like:

<!-- Navigation -->
<body id="home">
...
<ul>
	<li id="nav-home"><a href="#">Home</a></li>
	<li id="nav-about"><a href="#">About</a></li>
	<li id="nav-port"><a href="#">Portfolio</a></li>
</ul>

and it would work in conjunction with this CSS:

/* Make the current navigation item black by checking 
the id on the body tag; then apply the rule only 
to the corresponding navigation item */
body#home li#nav-home a,
body#about li#nav-about a,
body#port li#nav-port a
 {color:black;}

The main advantage of this technique is that you can copy and paste your navigation code between pages without changing anything. The disadvantage is that you must anticipate all the navigation possibilities in advance — if you go back and add a new navigation item to the HTML, you have to update the rule in your CSS too.