CSS Pseudo-Selectors

Selectors are an integral part of CSS. They help in targeting HTML elements when not using inline CSS.

Pseudo-Selectors can be called pseudo-elements or pseudo-classes depending on the job they are performing.

Pseudo-elements

Pseudo-elements are generally used to style specific parts of an element or inserting some content before or after it.

"::" is inserted after the element to indicate a pseudo-element. Some examples of pseudo-elements are:

::before:

"::before" is used to insert content before an element. The content to be inserted is specified in "content". For example:

p::before{
    content: url('bg.png');
}

Here, the image "bg.png" will be inserted before every paragraph (p) element.

::after :

"::after" is used to insert content after an element. The content to be inserted is specified in "content". For example:

p::after{
    content: url('bg.png');
}

Here, the image "bg.png" will be inserted after every paragraph (p) element.

Pseudo Classes

Pseudo-classes are used to define/target a unique state of an element.

":" is inserted after the element to indicate a pseudo-element. Some examples of pseudo-elements are:

:hover:

":hover" is used to introduce special specifications when the cursor hovers over the element. For example:

li:hover{
    background-color: #ffffff;
}

Here, the background color of the list (li) will be white when the cursor hovers over the list.

:focus

":focus" is used to introduce special specifications when the user focuses on the element. For example:

input:focus{
    background-color: #ffffff;
}

Here, the background color of the input field will be set white when the user clicks on it. It will be changed back to its original value when the user clicks someplace else.

:first-child

"first-child" is used to target the element which is the first of it's kind among many and is a child of another element. For example:

ul>li:first-child{
    background-color: #ffffff;
}

Here, the first li (list) item will be targeted which is also a child of a ul (unordered list) and it's background color will be changed to white.

:last-child

"last-child" is used to target the element which is the last of it's kind among many and is a child of another element. For example:

ul>li:last-child{
    background-color: #ffffff;
}

Here, the lastli (list) item will be targeted which is also a child of a ul (unordered list) and it's background color will be changed to white.

0
Subscribe to my newsletter

Read articles from saurabh suryavanshi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

saurabh suryavanshi
saurabh suryavanshi