Detail guide on CSS Selector with code examples.

Alok VermaAlok Verma
2 min read

CSS selectors are used to select a element from the DOM and apply CSS over it.

Universal Selector:

*{
    margin: 0;
    padding: 0;
}

This will select all elements in the document.


Element Selectors:

These selectors are used to select all the elements in the document.

h1{
    color: red;
}

This will select all <h1> in the document.


id Selectors:

These selectors are used to select all the elements with specific id in the document.

.id-name{
    background-color: #4d4d4d;
}

This will select only those elements which are given this id value.


Class Selectors:

These selectors are used to select all the elements with specific class in the document.

.class-name{
    color: red;
}

This will select only those elements which are given this class attribute.


Attribute Selectors:

These selectors are used to select all the elements with specific attribute.

img[alt = "hero image"]{
    border: 2px solid red
}

This will select only those <img> which has alt = "hero image" as its attribute.


Grouping Selectors:

Used to select various elements at once.

span, div, aside{
    border: 2px solid crimpson;
}

This will select all <span> <div> and <aside> elements in the document.


Combined Selectors:

This approach is used to select a element which is nested at various levels.

.class-name h1{
    color: red;
}

This will select all the <h1> present in the element present in the element which are given class-name as its class attribute


direct child Selectors:

This selector is used to select the elements which are direct child of the first element.

.first-ele > div{
    color: red;
}

This will select all the <div> which are direct child(Nested at first level) of the element with class value first-ele .


General sibling combinator:

This selector is used to select the following elements which are sibling of the first element.

.list-item ~ li{
    color: red;
}

This will select all the following <li> which are sibling(present at same Nesting level) of the element with class value list-item .


Adjacent sibling combinator:

This selector is used to select the elements which are immediate sibling of first element.

.list-item + li{
    color: red;
}

This will select <li> which is immediate sibling(present at same Nesting level) of the element with class value list-item .


9
Subscribe to my newsletter

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

Written by

Alok Verma
Alok Verma

I am a fullStack developer from India