CSCI 185: Fall 2022

Introduction to Programming for the Web

CSCI 185: Fall 2022

Fish by @akeatk

CSS Resources > 2. Selectors

W3Schools Reference

Overview

Selector Example Example description
.class .intro Selects all elements with class=”intro”
#id #firstname Selects the element with id=”firstname”
* * Selects all elements
element p Selects all <p> elements
element, element div, p Selects all <div> elements and all <p> elements
element element div p Selects all <p> elements inside <div> elements
element > element div > p Selects all <p> elements where the parent is a <div> element
element + element div + p Selects all <p> elements that are placed immediately after <div> elements
element~element p ~ ul Selects every <ul> element that is preceded by a <p> element

There is an excellent selector tester available on the W3Schools website that does a deeper dive into some of the more complex selectors.

Basic Selector Examples

Element Selector

Selects elements based on the element name

Example: h1 { color: red; }

ID Selector

Uses the id attribute of an HTML element to select a specific element, using the hash character (#):

Example: #my_tag { color: red; }

Class Selector

Selects elements with a specific class attribute. To select elements with a specific class, write a period (.) character, followed by the name of the class.

Example: .heading { color: red; }

Grouping Selectors

When you want to apply the same rule to many selectors, separate them with a comma:

Example: h1, h2, h3 { color: red; }