November 22, 2012

Basic Pseudo-elements in CSS


Pseudo-elements are another CSS selectors that is used to style the HTML elements. It contains pseudo selectors like first-letter, first-line which are used as styles and also :before and :after selectors which are used to insert additional texts into the HTML elements. Note that, this style cannot be applied on inline styles.

1. First-letter

In various newspapers and magazines, you may have come across the typographic effect where the first letter in the starting paragraph would appear bold, big and also with different font style. Similarly, the :first-letter pseudo-element gives you the functionality to style the first or starting letter of the element that is denoted.


#firstpara:first-letter {
    font-size:300%;
    color: orange;
}

You can see that the first letter in the paragraph has changed according to the style applied.

2. First-line

The first-line pseudo element is a style that can be applied to the first line of the element.


#firstpara:first-line {
    font-variant: small-caps;
    color: green;
}

You can see the changes that happened to the first line in the paragraph.

3. Before and After

The :before and :after pseudo elements are used to add texts before or after the specified element. In the course, this is now also used for many style functionalities.


<!-- This is HTML code -->
<p id="para">, your age is </p>


/* This is CSS code */
#para:before {
    content: "Balaji";
    color: green;
}

#para:after {
    content: "21.";
    color: green;
}

You can see from HTML code, where there is only ', your age is ' texts. Then the :before pseudo-element applies the 'Balaji' texts before the HTML content and the :after pseudo-element applies '21.' after the HTML content.

Note that it is mandatory to use the 'content' property in before and after pseudo-elements, or it would have no value in CSS styles.

No comments:

Post a Comment