Wednesday, January 03, 2007

CSS Starter Guide - Lesson 3: More on selectors

Lesson 3: More on selectors

Element selectors-Use the name of the element to apply styles to it. p{} selects all <p> elements.

Class selectors-Selects all elements that have a class attribute of a certain name. Class name is preceded with a dot ('.').

<p class="myClass">text</p>
.myClass{}

Id selectors-Selects an element with a certain id attribute. Only one element in a page can have the same id attribute. Id is preceded by pound sign('#').

<p id="myId">text</p>
#myId{}

Specificity-Certain types or combinations of selectors can help you drill down to the exact element(s) that you want so that you can make the right kinds of changes. Selectors in increasing specificity:

  • Element selectors
  • Class selectors
  • Id selectors

Combining Selectors-You may want to stack selectors to get the kind of precision that you need. I usually give unique regions of my pages an id attribute. Consult the code below:

<div id="header">
  <h1>page Title</h1>
  <ul class="nav">
    <li><a href="#">Home</a>
    <li><a href="#">Contact</a>
  </ul>
</div>

I would like all my navigations to have the same color:

.nav{color:white;}

I can increase the specificity a little by putting the element that I know will have the nav class:

ul.nav{color: white;}

But I would like to have the nav in the header to not have the bullets that are default for list items, so I select the nav that's in the header:

#header ul.nav{list-style: none;}

I would also like to make sure that the nav displays inline, like tabs, so I select all li elements that are children of ul elements with a class attribute of nav that are in the div with the id attribute of header.

#header ul.nav li{display: inline;}</code>

Quite a mouthful but it makes sense. If I had skipped any of those selectors I might grab the wrong elements so I want to make sure I'm using the right kind of specificity.

When you've gone too far-While making sure you are specific in your selectors, it is possible to go a little overboard. You start throwing gobs of classes and ids into your markup and you are going to find that your CSS and HTML are going to end up bloated and harder to maintain.

No comments: