Archive for the ‘css’ Category

Understanding CSS Selectors

Wednesday, February 22nd, 2006

Class Selector

Class selectors will select any element of a given class, and apply all of its attributes.

There are two ways class selectors are applied, solitaire(generic) class selectors or element class selectors. A generic class selector will be written in a stylesheet like:

.foobar { width:100%; color:#000; }
.foosandwich { float:left; clear:left; }

Whereas your element class selector will look like the following

p.foobar { font-size:1.4em; color:#121212; }
p.foosandwich { float:left; clear:left }
div.foo { width:80% background:#222222; }

ID Selector

ID selectors are almost identical to class selectors, with one major difference. As previously mentioned, class selectors are applied to one or more elements on a page, whereas ID selectors are applied to only one element on a page.

A general rule of thumb for me is to only apply ID selectors to elements that I know will only appear once on a page, and only apply them to specific elements such as h2, td, and tr. Most div tags will get class selector attributes, and all elements that I know or suspect will occur more than once in a single page. The only time I would use ID selector attributes on div tags would be on positioned elements, which generally occur only once a page.

Psuedo-Class

Psuedo-classes are used to add specific attributes/effects to specific selectors. We commonly see this with the a tag.

a:visited { color:#555; }
a:hover { color:#333; text-decoration:underline; }
a:active { color:#222; font-weight:bold; }

You can also apply psuedo-classes to element classes, as follows:

a.title:hover { color:#00cc00; text-decoration:underline; }
a.title:visited { color:#545454; }

New to CSS2, are psuedo element selectors, :lang, which allows the developer to specify a language to use in a specific element, and :first-child, which adds style to an element that is the first child of the specified parent element, :first-line will style the first line of a selected element, :first-letter will style the first letter of the selected element, :before and :after which will add generated content before and after, respectively, to a selected element.

p:first-child { text-indent:20px; }
h1:before { content: "Article "; }

You can read more on psuedo-classes here.