This website may use cookies. More info. That's Fine x
Welcome Login

Pseudo class and pseudo elements


Css

Pseudo-classes:

Pseudo-classes allow you to format items that are not in the document tree, ie: where there is no CSS selector available, like the state of a hyperlink.  Eg. active or visited.

Eg:

  • :first-child
  • :link
  • :visited
  • :hover
  • :active
  • :focus
  • :lang(n)

 

Styling links (anchor tags):

With pseudo-classes, you can style links in different ways in each of the four states:

a:link         is the selector for normal links
a:visited      is the selector for visited links
a:hover        is the selector for hover state
a:active       is the selector for active links

 

Pseudo class selectors should always be used/declared in the following order for specificity reasons:

1. a {}
2. a:link {}
3. a:visited {}
4. a:hover {}
5. a:active {}

 

You can also combine states if required, as long as the order (link and visited before hover and active) is maintained:

a:link, a:visited { color: blue; }
a:hover, a:active { color: red; }

 

 

Pseudo-elements:

Pseudo-elements allow you to style information that is not available in the document tree.

Eg: using standard selectors there is no way to style the first letter or first line of an element's content.

 

:first-line and :first-letter

:first-line selector: select  first line of an element, like a paragraph.

p:first-line {font-weight: bold; }

 

:first-letter selector: select first letter of an element, like a paragraph.

p:first-letter {font-size: 200%; font-weight: bold; }

 

Eg:

<html>

<head>
    <style type="text/css">
	    p:first-letter {font-size: 200%; font-weight: bold; }
    </style>
</head>
<body>
    <p>Once upon a time...</p>
</body>

</html>

 

Outputs:

css-pseudoelement1

 

:before and :after

These two pseudo-element selectors are used to insert generated content either before or after an element on the page.


Created on: Friday, March 18, 2011 by Andrew Sin