Contents

What are CSS Selectors and How They Work?

A CSS selector is an expression that determines which HTML elements a style applies to

Nov 16, 2023
1
min read

A CSS selector is an expression that determines which HTML elements a style applies to. It's a type of simple computer language that helps you identify which HTML elements the styles will affect. The syntax of a CSS selector is similar to that of an HTML tag, and the same rules apply in terms of what can be included.

What are the Different Types of CSS Selectors?

There are four types of CSS selectors: type, universal, ID, and class.

Type Selector: this type selects all elements with the same tag name as the selector. 

For example, p { } will style all the paragraphs on a page.

Class Selector: this type selects all elements with the same class as the selector. 

For example, .nav { } will only apply styles for any elements within the nav class.Type Selector: p {}Universal Selector: /**/ {}ID Selector: header {}Class selector: .nav {}

ID Selector: this type selects all elements with the same ID as the selector. 

For example, #header { } will only apply styles for header elements with an ID attribute value of "header".

Universal Selector: this type selects everything on a page (including text). 

For example, * { } will style all the elements on a page that don't have any other specific CSS selector applied to them.

Common Uses of a CSS Selector

The most common use of CSS selectors is for styling text on a webpage. For example, if we wanted to modify the copy across all paragraphs, all we would need to do is use the "p" selector and then add our desired style. Let's say we wanted to change the font size of the copy. The command below is what you would use:

p { font-size: 16px; }

This CSS rule will apply to all tags on the page, changing their size to 16px. Or what if you wanted to change the font color to red? The following command selects all “p” tags on the page and sets their text color to red.

p { color: red; }

A full guide or as we call them... Guidde on CSS Selectors is coming soon.

Sign up for Free
All articles