CSS Tutorial - CSS Pseudo Class








We can use CSS pseudo-class combined with selectors to style an element based on the state.

For example :hover will apply a style when the user hovers over the element specified by the selector.

Syntax

The following code shows the basic syntax to use CSS pseudo-class. We add the CSS pseudo-class to the selector and separate by :.

selector:pseudo-class { 
   property: value; 
}




Example

The following code shows how to use CSS pseudo-class to style an anchor for various states.


<!DOCTYPE html>
<html>
<head>
<style>
/* unvisited link */
a:link {<!--  www . j a  v  a2s  . c o  m-->
    color: blue;
}

/* visited link */
a:visited {
    color: yellow;
}

/* mouse over link */
a:hover {
    color: black;
}

/* selected link */
a:active {
    color: red;
}
</style>
</head>
<body>

<p><a href="#">This is a link</a></p>

</body>
</html>

The code above is rendered as follows:

a:hover MUST come after a:link and a:visited in the CSS definition in order to be effective.

a:active MUST come after a:hover in the CSS definition in order to be effective.





Pseudo-classes and CSS Classes

We can combine Pseudo-classes with CSS classes to style element.


<!DOCTYPE html>
<html>
<head>
<style>
a.highlight:hover {<!--from   w w  w  . jav  a 2s  .  c om-->
    color: #ff0000;
} 
</style>
</head>
<body>

<p><a class="highlight" href="#">CSS Syntax</a></p>
<p><a href="#">CSS Tutorial</a></p>

</body>
</html>

The code above is rendered as follows:

CSS Selector :focus

The :focus selects elements with focus.

An example showing how to use :focus CSS selector.


<!DOCTYPE HTML> 
<html> 
    <head> 
        <style type="text/css"> 
        :focus{ <!--  ww w.j  a v  a 2 s.com-->
            border: thin black solid; 
            padding: 4px; 
        } 
        </style> 
    </head> 
    <body> 
        <form> 
            Name: <input type="text" name="name"/> 
            <p/> 
            City: <input type="text" name="city"/> 
            <p/> 
            <input type="submit"/> 
        </form> 
    </body> 
</html>

The code above is rendered as follows:

CSS Selector :first-letter

The :first-letter selector adds style to the first letter of the specified selector.

An example showing how to use :first-letter CSS selector.


<!DOCTYPE html>
<html>
<head>
<style>
p:first-letter{<!--from  ww w .  ja  v  a  2s .co m-->
    font-size:200%;
    color:#8A2BE2;
}
</style>
</head>
<body>
    <p>java2s.com</p>
    <p>www.java2s.com</p>

</body>
</html>

The code above is rendered as follows: