# tagged: Comments Off

Phantom CSS

At the heart of CSS, of course, are its selectors. They are after all what allow us to apply styles to a given element in our (X)HTML. Sometimes though, there is a desire to apply a style based on an elements state. That is where pseudo-classes come into play. You’ve probably all used them at some point…but there may be more there than you realize. Their value makes it worth taking a closer look.

Static Pseudo-Classes

Pseudo-classes allow us to apply an invisible, or “phantom”, class to an element in order to style it. For example, let’s look at the element most often styled using pseudo-classes: the anchor tag (). Some anchor tags point to locations a user has already viewed, and some point to locations the user has not yet visited. Looking at the document structure, we can’t tell this. No matter if the link is viewed or not, it looks the same in (X)HTML. However, behind the scenes, a “phantom” class is applied to the link to differentiate between the two. We can access this “phantom” class with pseudo-class selectors, like :link and :visited. (Pseudo-classes are always prefixed by a colon.)

The :link pseudo-class selector refers to any anchor tag that is a link…that is any anchor tag that has a href attribute. The :visited pseudo-class selector does exactly what it sounds like…it refers to any link that has been visited. Using these pseudo-classes allows us to apply different effects to links on the page according to the visited state.

  1. a {color:blue;}
  2. a:link {color: red;}
  3. a:visited {color: orange;}


The above styles for example, will make any anchor tag that does not have a href attribute to be colored blue (line 1). Any link that has a href attribute, but has not been visited will be red (line 2). Finally, if a link is visited (line 3), then it is an orange color.

Another static pseudo-class is :first-child (The :first-child pseudo-class is not supported by IE6). The :first-child selector is used to select elements that are first children of other elements. This can be easily misunderstood. A lot of times, people will try to use it to select the first-child of an element. For example:

  1. Here is some text


Say we want to apply a style to the paragraph element. It is not uncommon to see people try to do this using the following style:

  • div:first-child {font-weight: bold;}


However, this is not how the pseudo-class works. If we think back to the concept of pseudo-classes essentially being “phantom” classes, then what we just did was apply a phantom class to the div like so:

  1. Here is some text