Deep dive into CSS Pseudo Elements.

27 / Jul / 2015 by Vibhor Kukreja 0 comments

We all are familiar with the Pseudo classes that css provides us to target certain elements that matches up certain criteria or state. And they are signified by a single colon followed by the pseudo class.

Syntax for pseudo class:

selector:pseudo-class {
    property:value;
}

Some of the basic examples of pseudo class, commonly used are:
:hover
:active
:visited
:first-child

Whereas, a Pseudo element is designed to target a certain part of an element. Which makes it different from the pseudo classes and it is signified by two colons followed by the name of the pseudo class. Since IE8 doesn’t works well with the two colon format, but you can also use the pseudo elements with the single colon format. This makes it support IE8, as all other latest browser also supports the single colon format.

Syntax for pseudo element:

selector::pseudo-element {
    property:value;
}

Some of the basic examples of pseudo elements, commonly used are:
::before
::after
::first-letter
::first-line
::selection

These pseudo elements allows us to style and add content to an existing element. You can use these pseudo elements as,

::before
It is used to inserts content before the content of the selected element/elements. To add up content before the selected element, you need to use the content property of CSS.

example

my-class::before {
	content : "*****";
	color : red;
}

This will insert five red star(asterisk) before the element “my-class”.

::after
It is used to inserts content after the content of the selected element/elements. To add up content after the selected element, you need to use the content property of CSS.

example

my-class::after {
	content : "*****";
	color : red;
}

This will insert five red star(asterisk) after the element “my-class”.

::first-letter
It is used to select the first letter of the specified selector. This will help you to give style specifically for your first letter of the text i.e. initial or dropcap.

example

my-class::first-letter {
    font-size: 80px;
    font-weight: bold;
}

::first-line
It is used to select the first line of the specified selector. This will help you to give style to the first line of the text.

example

my-class::first-line {
    font-weight: bold;
    color: green;
}

::selector
It is used to match the portion of an element that is been selected by a user on the screen.

example

my-class::selection {
    color: red; 
    background: white;
}
// selection  for Mozilla Firefox
my-class::-moz-selection {
    color: red; 
    background: white;
}

You can use these above described pseudo elements for creating custom icons, designs, layouts, etc. It gives you power to showcase your complex GUI designs in a more symmetrical manner and make the HTML code less complex and easier to maintain.

Hope it would Help!!

FOUND THIS USEFUL? SHARE IT

Leave a comment -