Fall 2026
  • Discord
  • Gradescope
  • Syllabus

On this page

  • Stylesheet Rules
  • Selectors
  • The Document Tree
  • Sibling Selectors
  • The Cascade
  • Spacing and Screens

CSS

Once a webpage has content, we can decide how people will see it. CSS (Cascading Style Sheets) controls the layout, colors, spacing, and fonts. We’ll write rules that apply to the elements we choose and see how to adapt a page to different screen sizes.

Stylesheet Rules

A CSS rule has two parts. The selector identifies the HTML elements to style. The declaration block, in curly braces, says how to style them. Each declaration sets a property to a value using the form property: value;.

This rule makes the text of every paragraph teal:

p {
    color: teal;
}

p is the selector, color is the property, and teal is the value. Add more declarations inside the same braces to change several properties at once.

A stylesheet is a collection of CSS rules. Several pages can share one stylesheet. Link to it from the <head> of each HTML document, and an edit to the stylesheet will apply to all those pages.

Our example is the campus Midnight Market, with event announcements and a food stall. Save this complete page as index.html, and create an empty style.css beside it. The CSS examples below go in style.css and all use this page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Midnight Market</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
<main id="night-market">
    <h1>Midnight Market</h1>
    <p class="notice">Bring an appetite. The salsa is on us.</p>
    <section class="stall">
        <h2>California Burritos</h2>
        <p>Steak, fries, and cheese. Extra salsa optional.</p>
        <ul>
            <li>Carne asada <span class="notice">sold out</span></li>
            <li>Bean and cheese</li>
        </ul>
        <p class="notice">Last batch at 10:30.</p>
    </section>
    <p>Next market: Friday after finals.</p>
</main>
</body>
</html>

<main> holds the page’s main content, and <section> groups the information about one stall. Add the paragraph rule above to style.css, save both files, and open index.html in a browser. Keep using these files for the examples below, saving and reloading after each change.

Selectors

A type selector chooses elements by their HTML tag. Classes and IDs let us select elements based on their purpose instead. A class is a reusable label: several elements can share it, even when they have different tags. An ID names one particular element and must be unique on the page. Class names and IDs have no appearance of their own; the stylesheet supplies it.

The two notice paragraphs and the sold-out span share class="notice". One rule makes all three bold, while another chooses the market’s container by its ID:

.notice {
    font-weight: bold;
}
#night-market {
    font-family: sans-serif;
}

The dot and hash belong in CSS selectors, not in the HTML attribute values.

An element can have several classes, separated by spaces in its class attribute. A selector without spaces can combine several conditions on the same element. A comma instead means “match either selector”; an element that matches both is still selected only once. An attribute selector checks a written attribute value.

For <p class="notice urgent">, both .notice and .urgent match. p.notice matches because the element is a paragraph with the class notice. [class="notice"] does not match: the full attribute value is notice urgent.

On the market page, p, .notice selects all four paragraphs and the sold-out span. The two notice paragraphs are each counted once.

The table below shows how selectors choose elements. (All the cheatsheets from this reading are available as a PDF here.)

Selector Selects
p Elements with the tag p
.notice Elements with the class notice
#top The element with ID top
p.notice Paragraphs that themselves have class notice
* Every element
h1, h2 Elements matching either selector, without duplicates
[href="next.html"] Elements whose href equals next.html

The Document Tree

Sometimes an element’s location is more useful than its label. We might want paragraphs inside a certain section or links inside the navigation menu. The browser represents HTML as a Document Object Model (DOM), which includes a tree of its elements. This tree records which elements contain which others.

An element’s parent is the element immediately containing it. Its children are the elements directly inside it. Its descendants include its children and every deeper level of nesting. Elements with the same parent are siblings.

In the market HTML, <main> has four children: the heading, mug reminder, stall section, and next-market paragraph. The sold-out span is a child of the first list item and a descendant of the list, section, and main element.

Midnight Market element tree. Main contains h1, p, section, and p. The section contains h2, p, ul, and p. The ul contains two li elements; the first li contains a span.

A combinator joins selectors by requiring a relationship between elements. A space means “descendant of”; > means “direct child of.” The element matched by the rightmost selector receives the style. The selectors to its left describe where that element must be.

Replace the first p rule with this one to color only the event announcements:

main > p {
    color: teal;
}

main p selects all four paragraphs, while main > p selects only the two directly inside <main>. p.notice selects paragraphs that have the class themselves. p .notice looks for a notice inside a paragraph, so it matches nothing on this page.

Sibling Selectors

Sibling selectors describe elements that occur beside each other rather than inside each other. The adjacent sibling combinator, +, selects the next element after a matching sibling. The general sibling combinator, ~, selects any later matching sibling. Both require the same parent and look forward in the HTML order. Whitespace between tags does not create another element.

The stall introduction immediately follows its heading. Add this rule to italicize it:

h2 + p {
    font-style: italic;
}

h2 ~ p would also select the last-batch paragraph, even though a list comes between them. Neither selector matches the next-market paragraph: it has a different parent from the <h2>.

The table below shows how combinators describe relationships between elements.

Combinator Relationship
main p A paragraph anywhere inside main
main > p A paragraph directly inside main
h2 + p A paragraph immediately after an h2, with the same parent
h2 ~ p A paragraph anywhere after an h2, with the same parent

Longer selectors combine these relationships. Start with the rightmost selector, then check whether each candidate has the required relatives.

For h2 ~ ul > li, start with each list item. Its parent must be a <ul>, and that list must have an earlier <h2> sibling. Both market menu items match.

To check your predictions, open the market page’s developer tools with F12 and go to Console. document.querySelectorAll finds matching elements; .length counts them.

document.querySelectorAll('main p').length     // 4
document.querySelectorAll('main > p').length   // 2
document.querySelectorAll('h2 + p').length     // 1
document.querySelectorAll('h2 ~ p').length     // 2

Omit .length to inspect the elements themselves. Try predicting ul .notice, ul > .notice, and li > .notice before running them.

The Cascade

An element can match several rules, and those rules can disagree. The cascade is CSS’s system for deciding which declaration applies. For ordinary rules in a single stylesheet, a more specific selector takes precedence. An ID selector outranks a class selector, which outranks a type selector. When selectors have equal specificity, the rule written later wins.

Both rules match the notice paragraphs:

.notice {
    color: teal;
    font-weight: bold;
}
p {
    color: black;
}

Their text is teal: the class selector wins even though the type selector appears later. If another .notice { color: purple; } rule follows both, the text becomes purple.

Conflicts are resolved one property at a time. Setting an element’s color does not replace a font-weight declaration from another rule. Some properties, including text color and font family, are also inherited: a child uses its parent’s setting when it has no setting of its own.

The notice paragraphs above remain bold whichever color wins. Our #night-market font rule supplies a sans-serif font to the container and, through inheritance, its contents. If a paragraph has its own font-family declaration, that declaration supplies its font instead.

In main > p, the two type selectors make it more specific than p alone. The > describes a relationship but does not add specificity itself.

Spacing and Screens

CSS treats each element as a box. Padding is the space between the content and its border. Margin is the space outside the border that separates the element from its neighbors. The background color extends through the padding.

Give the market paragraphs space inside and outside a border:

p {
    padding: 12px;
    border: 1px solid teal;
    margin: 20px;
}

Change the padding and margin separately to see which gap moves.

A pseudo-class selects an element in a particular state. :hover matches while the pointer is over the element, so its appearance can respond to the visitor without changing the HTML.

Change the final market announcement to include a link:

<p>Next market: <a href="next-market.html">Friday after finals</a>.</p>

Create next-market.html with a short announcement, then add these rules:

a {
    color: teal;
}
a:hover {
    background-color: #f2d6d9;
}

Responsive design adapts a page to the available screen space. A media query applies a group of CSS rules only when a condition is true. A width condition lets us use different spacing or text sizes on a phone and a laptop while keeping the same content.

Add this metadata in the HTML <head> so a phone uses its actual screen width:

<meta name="viewport" content="width=device-width, initial-scale=1">

Then add a rule for narrow screens:

@media (max-width: 600px) {
    p {
        margin: 8px;
    }
}

At 600 CSS pixels wide or narrower, this later paragraph rule changes the margin to 8 pixels. On wider screens, the earlier 20-pixel margin applies. Resize the browser across the boundary to check both cases.

The table below shows properties and rules for styling a page.

Property or rule Purpose
color Text color
background-color Color behind content and padding
font-family Font choice, such as sans-serif
font-size Text size
font-weight Text weight, such as bold
font-style Text style, such as italic
padding Space between content and border
border Border width, style, and color
margin Space outside the border
a:hover Select a link while the pointer is over it
@media (max-width: 600px) Apply enclosed rules at widths of 600 CSS pixels or less
@media (min-width: 600px) Apply enclosed rules at widths of 600 CSS pixels or more