November 21, 2012

Basic Pseudo-classes in CSS


Pseudo classes are CSS styles that is applied on HTML elements. They give some functionality to the HTML element either statistically or dynamically with or without certain physical movements by using mouse pointers etc. But, you must understand that this style cannot be used as inline styles.

1. Hover

Hover pseudo-class is most popularly used in anchor links. But this pseudo class can also be used in other HTML elements.


p:hover {
    background-color: yellow;
}

The above code explains how a paragraph has a normal state but changes its current state when the mouse pointer hovers or moves around that particular element. This can similarly be applied to other elements in HTML.

2. Focus

Well when hover pseudo class is used for dynamic mouse movements, focus pseudo class can be used as dynamic selectors with either tab or mouse clicks for a particular element.


a:focus {
    background-color: orange;
    color: #333;
    text-decoration: none;
}

Other than link elements, focus pseudo-class can also be used in forms. They are mostly used under input elements, textarea, etc...


input:focus , textarea:focus {
    border: 1px solid orange;
    background-color: yellow;
}

Due to inconsistencies among different browsers and adaptability to various devices, it is better to use focus pseudo-class with other close relational pseudo-classes like hover and active. This gives flexibility and credibility to the styles you apply.

An example style will look like,


a:hover,a:focus,a:active {
    background-color: orange;
    color: #333;
    text-decoration: none;
}

3. First-child

First-child pseudo-class helps to style the first element along its identical sibling elements.

Let's look an example HTML code first,


<p><strong>Love</strong> doesn't make the world go around. <strong>Love</strong> is what makes 
the ride worthwhile.</p>

Now applying first-child pseudo element on the strong element,


p strong:first-child {
    color: orange;
}

You can see that the style applied is only applied on the first strong attribute and not the second one because of the first-child pseudo-class.

No comments:

Post a Comment