Looking for the previous guiStuff?

It's still here, the content didn't go anywhere. You may want to check out this new guiStuff though -- It's rather informative.

References/Tutorials:


Intro Documents:


guiStuff:






::Stuff for the multi-spec coder;

Coding, formats, standards, and other practical things.

 Home  //  CSS Articles  //  CSS Selectors: Part 1 

<!-- CSS Articles

CSS Selectors: Part 1

Knowing how to apply CSS to a document takes more than memorizing all of the CSS properties and remembering how the document flow works. Of course, you could 'make it work' by making a new class for every element on your page and having a 40Bk .css file that loads along with it, but that's not practical, on many levels. To properly implement CSS, you need to know how to use selectors. Selectors define type(s) of HTML element(s) the styling (whatever's between the { }) applies to. They're the "other side" of a CSS style rule definition.

But First!

A prerequisite to properly implementing selectors is understanding the Document Tree. If you haven't already, it's recommended you go over the Document Tree article which details how the document tree is applied to HTML/XHTML documents.

CSS Selectors and Browser Support

The CSS Selector tells the renderer of the document (usually the browser) to which elements to apply each CSS style rule to. There are many kinds of CSS Selectors, and unfortunately quite a few of them are not properly supported by modern browsers.
Generally speaking, The Opera browser supports the vast majority of CSS selectors. If your CSS validates, but it doesn't seems to display properly on the browser you're currently using, you can always launch Opera and there's a good chance you'll see into "CSS Future".
Next comes Firefox, and the rest of the Mozilla-based browsers. In terms of Firefox versions, since version 1.5 it's supported most of the W3C's recommendations of current CSS implementations (remember that many of the specs are "recommendations", so you can't fault software developers for not implementing each and every feature if it might change in the next draft), but strictly speaking, not all.
Next on the list, is Internet Explorer 7. in IE7, the IE development team had made great efforts to achieve CSS and other standard compliance, and the results aren't bad (this is coming from someone who's followed the development of IE7 through most of the Beta releases, and wasn't expecting much from the final version, but overall, it was better than I had anticipated, in terms of standards compliance). While you should still check IE7 along with Firefox, for the most part, you won't see many differences, and the ones you do see will be relatively easy to fix, if you spot the propety that's 'causing the glitch'. As far as selector support, IE7 is behind Firefox, but that's really not the major problem.
The major problem is Internet Explorer 6. Of course, Internet Explorer 6 is the major problem for standards compliance in general, but it didn't skip selectors. As I describe selectors by type, I'll note which ones are supported by which browsers. You'll see that IE6 is the most significant cap for most of them. We have to take into consideration that IE6 is still in very widespread use, and will continue to be so for at least the end of 2007 (or so the estimates tell us).
In Part 1 of CSS Selectors, we'll only cover selectors which are supported by all of the above mentioned browsers. Part 2 will tackle the ones with which you'll start running into problems in.

But enough gloom and setbacks. On to selector types.

Choose how to Choose

There are multiple ways to select elements to style on the document. You have to choose how to select the elements which you want to style, and remember that multiple style rules overlap. What this means is, if one element is covered by more than one rule, then all of the rules that apply to it, will apply to it. This is a very good thing, you will come to discover. The simplest example would be that you want all of the fonts on your page to be uniform (say, Verdana), but you want different elements within the page to have different font-sizes and font-weights. Another familiar scenario is that you'd like the text on your page to be white, and the background to be black, but apart from that, you're going to be using different fonts of different sizes. This, again, is easy to achieve with selectors that select 'overlapping' elements. We'll cover more of this when we get to Selector Structuring.

The Type Selector

The Type Selector is the easiest to understand, and easiest to implement selector. It applies a CSS Style Rule to an HTML/XHTML element. For example:

body { margin: 0; padding: 0; background-color: #FFF; }

The above Style Rule applies solely to "elements" of type BODY. Incidentally, there's only one. This is a common way to rid the page of its variable, and browser-dependant margins (and in some browsers, padding), and to set the background color while you're at it. Let's look at another type selector implementation:

p { font-size: 0.9em; text-indent: 0.5em; padding: 2px; }

This is a common styling of a paragraph (the P element). The font-size has been set to 0.9em (or 90%) of the parent element, a padding of 2px has been added, and a text-indent of 0.5em has been added, which will only effect the first line of text within the block. Do you see the advantage of composing a style rule this way? It makes no assumptions at to the font-family, or to the absolute font-size of the parent element. It doesn't care what the color scheme is. It applies its rules of styling to what's relevant to it, and it alone. This, again, touches on the subject of Selector Structuring, but why not sneak in some extra information here an there if I can (call it standards propaganda...). Of course, this, by itself, isn't very useful, since it will target every single P element on the page, which is a bit unrestrained. We'll need to get to Descendant Selectors and Classes before we can properly select just what we want, within the contained areas we want it.

Something which should be covered early on is multiple selection. This allows you to place multiple selectors before a single style rule, simply be dividing them by commas:

h1, h2, h3, h4 { color: #444; }

This does exactly what you'd expect it to do. It applies color: #444; to all H1, H2, H3, and H4 elements in the document.

Universal Selector

When used by itself, the Universal Selector only appears in one way (usually, when it's a document that's intended for the web), and is rather limited in use:

* { font-family: Trebuchet MS, sans-serif, Arial, Helvetica; }

It literally selects every element in the document, so used by its own, it's either used for very short documents, or for Print Media CSS Documents. It does have use when used in conjunction with other selectors, like Adjacent Selectors, but this is hindered by the old IE6 (we'll get to that in Adjacent Selectors, in Part 2).

Descendant Selectors

With Descendant Selectors you're getting more specific about which elements you're going to style. Descendant Selectors can actually refer to Types, Universals, IDs, Classes, and Attribute Selectors, it just means that you're selecting by addressing the elements you want using their parents to guide the Style Rule to its targets. Visually, this is easier to understand. We'll start with some HTML code:

<div> <h3>Post Title</h3> <em>Post Date</em> <p>Post Contents <i>Author</i></p> </div>

The above code produces this Document Tree:

Document Tree 4


Now we'll use Descendant Selectors to select the element types, and then their descendants, which we want to style:

div h3 { text-decoration: underline; } div i { color: #0000CC; }

The first rule is looking for any H3 elements which are descendants of any DIV elements in the document. The second rule is looking for any I elements which are descendants of, again, any DIV elements in the document. Remember that they don't have to be direct-descendants, any descendant element that matches will be the target of that rule. In the above document, here's what it matched:

Document Tree 5


Both the H3 element and the I element were descendants of the DIV element, and so each respective Style Rule was applied to each element. This is getting more specific, but it's still somewhat broad. You'll still need Classes and IDs to properly target (select) just the elements you want and not catch something else in the document that happened to have the same relationship structure.

Class Selectors

The Class Selectors are the most often-used, and over-used type of selector. They're usually the first selector that people who are learning CSS are introduced to, and thus it becomes the one they rely on the most. This is not without reason, however. You're telling the renderer of the document to specifically select an element with a specific name. No ambiguity whatsoever. However, as the person who's designing both the style and the structure, you can make sure that there's no ambiguity by combining Class (and ID) Selectors with Type and Descendant Selectors, and creating both less Markup and less Style Rules (once again, this has to do with Selector Structuring, which will be properly covered in a separate article).

Let's take the HTML from above and tweak it a bit:

<div class="posting"> <h3>Post Title</h3> <em>Post Date</em> <p>Post Contents <i>Author</i></p> </div>

This time, I've added a class attribute to the DIV element. Now, by combining several types of selectors, I can achieve different goals:

.posting { font-family:Georgia, "Times New Roman", Times, serif; } .posting h3 { text-decoration: underline; margin: 0; } .posting p { margin: 0.4em; } .posting em { font-size: 0.8em; } .posting p i { display:block; color: #0000CC; }

Ok, so that might have been a bit too many Style Rules for one code block, but the big picture is important in this case. The first rule sets the font-family of the posting class. Remember that the font-family property is inherited, so I don't have to worry about the rest of the elements within the DIV element which I've styled with the posting class.
The next rule is a Class/Descendant rule. I'm selecting an element type which is a descendant of any element that was styled using that specific class. In this case, I'm selecting any H3 element which is a descendant of any element which was styled by the posting class. Any element matching this description will be assigned a text-decoration property, and a margin property.
The third and fourth rules are just like the second. This time, they're selecting P and EM elements, and assigning them margin, and font-size properties, respectively.
The last rule is technically the same as the previous three rules, except I'm being very specific about which element I want to style. I'm looking for an I element, which is a descendant of a P element, which is a descendant of any element which was styled by the posting class. In many programming languages this would be considered object-orientation, but here it's more like navigating the Document Tree. You're basically zooming-in on your target, and making sure that nothing else gets "accidentally styled" along the way. If there was an I element within the DIV element, but not within the P element, it would not have been effected.

Another thing to mention about Class Selectors, is that a single element can be styled using more than one class. It's easier than it sounds:

.greenish { color:#009966; } .biggie { font-size: 1.2em; font-weight: bold; } <span class="greenish biggie">Some Text</span>

This normally finds its uses in very large style sheets, with dozens of rules, where you have many overlapping qualities and you can narrow things down by assigning more than one class to a single element. This also finds use in style-sheet-switching, where you'd like to switch a color scheme, for example. You have one .css file that sets everything but the colors for your pages. Then you have another one that "houses" the color scheme. In that file, you don't name color classes like "Maroon" or "Hazel" -- instead, you assign names for the various elements that will be colored by the different hues of the color schemes around the page, like "heading_color", or "darker_comment". Beware, however, that this leads to bloated Markup and confusing fixes later on. You're going to have to find a balance if you're going to use multiple class assignments, since it can make the whole point of CSS (separating style from structure) go out the window if you're not careful.

ID Selectors

ID Selectors are similar to the Class Selectors in how they operate, except that they look for the common HTML/XHTML ID attribute. This attribute is used for other things, unlike the class attribute which is designed for CSS use. Forms use IDs to identify value containers, and JavaScript uses them as direct handles to elements on the document. Also, there can only be one ID of each name assigned to one element within a document. This is simply the nature of the web standards, and isn't CSS-specific. Using IDs to style elements has several advantages: First, if you're using JavaScript on elements you're going to style, then you're already using IDs, so why identify an element twice? Second, if you really only have one "thing" (that's a technical term) of its kind on a page (let's say, a right column), this will make sure you don't assign the same handle/identification to more than one element on the document.

Here's how ID Selectors are implemented:

#sign_post_a { color: #800; } <span id="sign_post_a">Some Text</span>

It's the same as Class Selectors, except with a # instead of a .. You can also use descendant selection just like the class/type selection example above. It should be noted that IDs are commonly reserved by designers for DIV elements and SPAN elements, although this isn't written in stone, it's just what you'll usually find when you're looking over the source of pages with interesting CSS implementations (which, by the way, is a highly recommended method of education).

Half-Time

That's it for CSS Selectors Part 1. In Part 2 we'll get into the cool pseudo-classes (a:hover!), and the more gritty Selector Types, which aren't really gritty, they're simply not supported properly by enough browsers.


Return to the CSS Articles section, or go the to Main page.





Looking for the old guiStuff?

It's still here, the old content didn't go anywhere.