Learn css: Selectors

Element Selector

Selects HTML elements based on their tag name. This is the most basic selector type in CSS and applies styles to all instances of a particular element on a page.

example code

In this example, all <p> elements on the page will have blue text.

Class Selector

Selects HTML elements with a specific class attribute value. Classes allow you to group together multiple elements and apply the same styles to them.

code example

In this example, all elements with class="classname" will have red text.

ID Selector

Selects a unique HTML element based on its id attribute value. IDs are intended to be unique on a page and are often used to identify specific elements for scripting or styling purposes.

code example

In this example, the element with id="my-id" will have a yellow background.

Descendant Selector

Selects an HTML element that is a descendant of another element. This selector allows you to apply styles to elements nested within other elements.

code example

In this example, all <li> elements that are descendants of a <ul> element will have bold text.

child Selector

Selects an HTML element that is a direct child of another element. This selector is similar to the descendant selector, but only applies styles to immediate children rather than all descendants..

code example

In this example, all <li> elements that are immediate children of a <ul> element will have underlined text.

Adjacent Selector

Selects an HTML element that is immediately preceded by another element. This selector allows you to apply styles to the element immediately following a specific element.

code example

In this example, all <p> elements that immediately follow an <h2> element will have italic text.