CSS Selectors

CSS selectors are used to select the HTML elements on which you want to apply styles. There are several different types of CSS selectors, each with its own unique syntax and use case.


Why CSS selectors are important?

CSS selectors are crucial for focusing on particular elements. It enables CSS writing without changing the appearance of the rest of the page.

To focus on particular items on a page, you can use a variety of selectors. When styling a number of items that are all connected in some way, this is useful.


Basic Selectors

Universal Selector

A universal selector selects all the elements on the page. it is denoted by an asterisk(*) symbol.

Type Selector/ Individual Selector

The simplest selector is the type selector, which chooses based on the tag name. For instance, if we choose the <p> tag, the document's entire <p> tag CSS will be changed.

Class & ID Selector

ID

The ID of an element is unique in the page, id is used to select a unique element on the page. To select an element with a specific id you have to use ' # ' followed by the id.

Class

Class is used to group elements and give CSS so that you don't have to write the same CSS for different elements. To select an element with the class you have to use period( . ) followed by the class name.

The id should not be used to group elements because they are distinct in and of themselves; instead, use classes to group elements.


Grouping Selectors

Chained Selectors

And selector is another name for chained selector, where both class names must be written without spaces.

Combined Selectors/ Selectors Lists

A , selector is used to group selectors separated by a comma.

Combinators

Descendant combinator / Inside an Element

The descendant selector is made of two or more elements separated by space.

Direct Child

The Child Selector is used to match every element that is a specified element's child. Child selector (>) is placed between two CSS selectors.

Sibling

General sibling combinator

The ~ combinator selects siblings. This means that the second element follows the first (though not necessarily immediately), and both share the same parent.

Adjacent sibling combinator

The + combinator matches the second element only if it immediately follows the first element.


Pseudo Elements

A pseudo-element is like adding or targeting an extra element without having to add more HTML.

::before

::before selector is used to add content on the page before the element without using HTML.

::after

::after selector is used to add content on the page before the element without using HTML.