CSS Selectors: The Detailed Guide

CSS Selectors: The Detailed Guide

What is a selector?

CSS selector is used to select the HTML elements that we want to style. There are so many selectors which we are using to style out HTML documents.

Basic selector

1. Universal Selector

This selector selects all the elements on a webpage.

* {
        color: blue;
        font-size: 16px;
}

2. Type Selector

It is also called Element selector. This selector is used to choose the element of that type.

p {
        text-align: center;
        background-color: aqua;
}

3. Class Selector

This selector is used to select the particular element with that class. It is represented by a Dot symbol (.)

.pink{
        color: pink;
}
      .bg-blue{
        background-color: blue;
}

4. ID Selector

This Selects the element with a unique id denoted by a specific id inside the element. It is represented by a Hash symbol(#)

#user-profile {
        padding: 20px;
}

let's understand some advanced selectors that are called Combination Selectors used to select the combination of 2 or more selectors.

Combination Selector

1. Descendent Selector

It selects the elements that are descendent of the first element. It is also called inside an element.

div ul li {
        border: 2px dashed white;
        font-weight: 400;
        font-size: 20px;
}

2. Child Selector

The Direct Child Selector selects the elements that are direct children of the first element.

section > h4 {
        font-family: "Courier New", Courier, monospace;
}

3. Sibling Selector

General Sibling Selector

The general sibling selector selects all elements that are siblings of the first element and come after the first element.

.div ~ p {
        background-color: blue;
}

Adjacent Sibling Selector

The adjacent sibling selector selects an element that is siblings of the first element and comes directly after the first element.

.div + p {
        background-color: blue;
}

4. Or Selector

It select Html elements that match any selector in the list.

div , a{
    border: 1px solid black;
}

5. And Selector

It selects elements that match all the selector combinations in the list.

div + a{
    border: 1px solid black;
}

Pseudo selector

There are two types of pseudo selectors.

1. Pseudo Element

Pseudo element is used to style the specified part such as create an empty element directly before the children of selected element.

div::before {
  content=" "
}
div::after {
  content=" "
}

2. Pseudo Class

It is used to define a special state of an element such as hover, focus, first child, last child, nth-child

li:hover {
  background-color: black;
  color: white;
}