CS396: Spring 2022

Intro to Web Development

CS396: Spring 2022

CSS Resources > 2. Selectors

Login to LinkedIn Learning via Northwestern

In order to apply styling to one or more of an HTML element’s style properties, you have to tell your web browser which element you want to style (using a selector). The videos and code samples below describe how selectors work, as well as the various types of selectors.

LinkedIn Learning Videos

Type and universal selectors 3:20
Class and id selectors 3:05
Class and id selector exercise 3:28
Descendant selectors 3:48
Grouping selectore 1:38

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; }