CSS pseudo-classes
A pseudo-class can be defined as a keyword which is combined to a selector that defines the special state of the selected elements. It is added to the selector for adding an effect to the existing elements based on their states. For example, The “:hover” is used for adding special effects to an element when the user moves the cursor over the element.
The names of the pseudo-class are not case-sensitive.
Syntax
A pseudo-class starts with a colon (:). Let’s see its syntax.
Although there are various CSS pseudo-classes, here we are going to discuss some of the most commonly used pseudo-classes. The widely used CSS classes are tabulated as follows:
pseudo-class | Description |
---|---|
:active | IIt is used to add style to an active element. |
:hover | IIt adds special effects to an element when the user moves the mouse pointer over the element. |
:link | IIt adds style to the unvisited link. |
:visited | IIt adds style to a visited link. |
:lang | IIt is used to define a language to use in a specified element. |
:focus | IIt selects the element which is focused by the user currently. |
:first-child | It adds special effects to an element, which is the first child of another element. |
Let’s discuss the above pseudo-classes, along with an example.
:hover pseudo-class
This pseudo-class adds a special style to an element when the user moves the cursor over it. If you want to make it effective, it must be applied after the “:link” and “:visited” pseudo-classes.
Example
:active pseudo-class
It applies when the elements are clicked or activated. It selects the activated element.
We can understand it with the example given below.
Example
:visited pseudo-class
It selects the visited links and adds special styles to them. Its possible values can be any color name in a valid format.
Example
:lang pseudo-class
It is helpful in documents that require multiple languages. It allows us to define special rules for different languages.
Example
In this example, we specify p:lang(fr) which selects the elements having attribute lang=”fr”.
:focus pseudo-class
It selects the elements that are currently focused on by the user. It is generally used in input elements of the forms and triggers when the user clicks on it.
Example
:first-child pseudo-class
It matches a particular element, which is the first child of another element and adds a special effect to the corresponding element.
Note: We have to declare a <!DOCTYPE> at the top of the document to make “:first-child” pseudo-class to work in IE8 and its earlier versions.
The following illustration explains it more clearly.
Example
The simple tooltip hover
A tooltip specifies extra information about something when the user moves the cursor over the element. Let’s create a tooltip by using the “:hover” pseudo-class.
Example
CSS classes and pseudo-classes
The classes in CSS can be combined with pseudo-classes. We can write it as-
Syntax
We can understand it with the following example.
Example