Pseudo-classes

Pseudo classes are bolted on to selectors to specify a state or relation to the selector. They take the form ofselector:pseudo_class { property: value; }, simply with a colon in between the selector and the pseudo class.

Links

link, targeting unvisited links, and visited, targeting, you guessed it, visited links, are the most basic pseudo classes.

The following will apply colors to all links in a page depending on whether the user has visited that page before or not:


a:link {
    color: blue;
}

a:visited {
    color: purple;
}

Dynamic Pseudo Classes

Also commonly used for links, the dynamic pseudo classes can be used to apply styles when something happens to something.

  • active is for when something activated by the user, such as when a link is clicked on.
  • hover is for a when something is passed over by an input from the user, such as when a cursor moves over a link.
  • focus is for when something gains focus, that is when it is selected by, or is ready for, keyboard input.

a:active {
    color: red;
}

a:hover {
    text-decoration: none;
    color: blue;
    background-color: yellow;
}

input:focus, textarea:focus {
    background: #eee;
}

First Children

Finally (for this article, at least), there is the first-child pseudo class. This will target something only if it is the very first descendant of an element. So, in the following HTML…


<body>
    <p>I’m the body’s first paragraph child. I rule. Obey me.</p>
    <p>I resent you.</p>
...

…if you only want to style the first paragraph, you could use the following CSS:


p:first-child {
    font-weight: bold;
    font-size: 40px;
}
This entry was posted in Uncategorized. Bookmark the permalink.