Understand Pseudo-classes in CSS


Sometimes, you may want to style an element based on something other than the structure of the document. For example: the state of a link (visited? hover? … etc) or form element (focused? for example).

So, How to do this using CSS?

This can be done using a pseudo-class selector.

Pseudo-class starts with colon then the class name, :link – :hover – :visited .. and so on

Here are some examples:

Makes all unvisited links Black:
a:link { color: black; }

Makes all visited links Brown:
a:visited { color: brown; }

Makes links red when hovered:
a:hover { color: red; }

Makes links red when activated or focused by ketboard:
a:focus, a:active { color: red; }

Makes table rows green when hovered over:
tr:hover { background-color: green; }

Makes input elements with dashed border when focus is applied:
input:focus { border: 1px dashed black; }

:link and :visited are known as link pseudo-classes and can only be applied to anchor elements.

:hover, :active, and :focus are known as dynamic pseudo-classes and can theoretically be applied to any element. Most modern browsers support this functionality.

Unsurprisingly, IE 6 only pays attention to the :active and :hover pseudo-classes when applied to an anchor link, and ignores :focus completely.

IE7 supports :hover on arbitrary elements but ignores :active and :focus.

You can use pseudo-classes together to create more complex behaviors, such as styling the hover effect on visited links different from those on unvisited links.

Makes all visited links olive on hover:
a:visited:hover { color: olive; }

Simple, Isn’t it?

Also, you can combine pseudo-classes with normal classes, For example:

Makes all visited links yellow only if they have class .red:
a.red:visited { color: yellow; }

The :first-child pseudo-class matches a specified element that is the first child of another element.

But For :first-child to work in IE a must be declared correctly.

Match the first paragraph element:
p:first-child { color: blue; }

Azzam has been developing websites nearly 4 years now. You can check out his latest website on Designer Eyeglasses which reviews and lists the best Designer Eye Glasses


Disclosure: Some of our articles may contain affiliate links; this means each time you make a purchase, we get a small commission. However, the input we produce is reliable; we always handpick and review all information before publishing it on our website. We can ensure you will always get genuine as well as valuable knowledge and resources.

Recommended Content for you:

Related Articles You May Like:

Article Published by Souvik Banerjee

Web Developer & SEO Specialist with 10+ years of experience in Open Source Web Development, specialized in Joomla & WordPress development. He is also the moderator of this blog "RS Web Solutions".