CSS Selectors Summary

A CSS selector tells the browser which HTML elements a style rule should affect.

p {
	color: blue;
}

This selector targets every paragraph element on the page. The declarations inside the braces control how those paragraphs look.

Element Selectors

An element selector targets every HTML element with that tag name.

h2 {
	font-size: 28px;
}

p {
	line-height: 1.5;
}

Element selectors are useful for broad default styles.

Class Selectors

A class selector targets elements with a matching class attribute. In CSS, class selectors start with a period.

<p class="intro">Welcome to the site.</p>
.intro {
	font-size: 20px;
	font-weight: bold;
}

Classes are reusable. Several elements can share the same class, and one element can have more than one class.

ID Selectors

An ID selector targets the element with a matching id attribute. In CSS, ID selectors start with #.

<section id="contact">Contact information</section>
#contact {
	background: lightgray;
}

An ID should normally appear only once on a page. For reusable styling, classes are usually the better choice.

Descendant Selectors

A descendant selector targets elements inside another element.

.card p {
	color: gray;
}

This rule styles paragraphs inside elements with the card class. It does not style every paragraph on the page.

Selectors Affect The Cascade

More specific selectors can override broader selectors. The CSS Cascade lesson explains how the browser decides which matching rule wins.

Interactive Demo

<h2>This is a heading</h2>
<p>This paragraph is selected by its class.</p>
<p>This paragraph is selected by its class.</p>

This is a heading

This paragraph

This paragraph

<h2 class="highlighted">This is a heading</h2>
<p class="larger">This paragraph is selected by its class.</p>
<p class="smaller">This paragraph is selected by its class.</p>

This is a heading selected by its class.

This paragraph is selected by its class.

This paragraph is selected by its class.

Code Sandbox

AI Tutor