Why CSS Exists

Getting Started

The Driving Problem

What font and size does <h1>Introduction</h1> produce? Whatever the browser’s default is. HTML says what something is, not how it should look. Early HTML tried to fix that with attributes on every element, such as <table border="2" bordercolor="black">, which meant repeating the same styling on every page and every tag.

Without style sheets
With style sheets
  • Appearance is the browser’s choice unless you override it
  • Overrides are attributes on each element
  • Changing a color means editing every page
  • Content and formatting are tangled together
  • You specify the style instead of accepting the default
  • A rule is written once and applies everywhere it matches
  • Changing a color means editing one line
  • Content stays in HTML, formatting lives in a .css file

Separate Style From Content

Content, meaning what to display, is in HTML files. Formatting, meaning how to display it, is in separate style sheets. The two are linked by selectors, most often the class attribute: <span class="test"> in the HTML, .test { … } in the CSS.

DRY: Don’t Repeat Yourself. Define style information once and use it in many places. The test: can you make all the text in the app slightly bigger, or switch to a new company color, by changing one rule? If yes, the styles are organized correctly.

How This Sheet Is Organized

  1. Getting Started: a stylesheet to copy and how CSS reached its current form.
  2. Rules and Selectors: the anatomy of a rule, how to target elements, pseudo-classes, and which rule wins when several match.
  3. Properties: color, the box model, units, sizing, text and backgrounds.
  4. Layout: display, position, flexbox and grid.
  5. Worked Example: the lecture’s full example with its output, plus notes on CSS in the real world.

Source: CS142 lecture notes on Cascading Style Sheets by Mendel Rosenblum, Stanford, reformatted for this site.

The Stylesheet Template

Getting Started

Copy This

Save it as styles.css next to your HTML file and attach it with one line in the <head>. Every page that links the file picks up every rule.

styles.css

/* styles.css */

:root {
    --ink: #222222;        /* text */
    --paper: #ffffff;      /* page background */
    --accent: #0057b8;     /* links and highlights */
}

* {
    box-sizing: border-box;
}

body {
    margin: 0;
    font-family: Tahoma, Arial, sans-serif;
    font-size: 16px;
    line-height: 1.5;
    color: var(--ink);
    background: var(--paper);
}

h1, h2, h3 {
    margin: 1.5em 0 0.5em;
    line-height: 1.2;
}

p {
    margin: 0 0 1em;
}

a {
    color: var(--accent);
}

a:hover {
    text-decoration: none;
}

img {
    max-width: 100%;
    height: auto;
}

.container {
    max-width: 960px;
    margin: 0 auto;
    padding: 0 16px;
}

.shaded {
    padding: 8px 12px;
    background: #d0d0ff;
}

In each HTML file

<head>
    <link rel="stylesheet" href="styles.css">
</head>
BlockWhat it does
:root { --ink: ... }Custom properties, the CSS version of variables. Change the company color here and every rule using var(--accent) follows.
* { box-sizing: border-box; }Makes width include padding and border, so a 200px box is 200px wide. See the Box Model tab.
body { ... }The base font, size, color and background. Most text properties inherit from here.
h1, h2, h3 { ... }One rule for several selectors, separated by commas.
a:hover { ... }A pseudo-class: applies only while the mouse is over the link.
.container { ... }A reusable class: <div class="container"> centers content at a readable width.

Three Places Styles Can Live

Separate style sheetBest way
Page-specific and element-specific
<link rel="stylesheet" type="text/css" href="myStyles.css">

One file shared by every page. Changing it changes the whole site, and the browser caches it.

<style>
    body { font-family: Tahoma, Arial, sans-serif; }
</style>

<div style="padding: 2px; color: red;">

A <style> block in the head applies to that page only. A style attribute applies to that one element only. Both are fine for one-offs; neither scales.

To attach a stylesheet and know that it worked:

  1. Save the CSS as styles.css in the same folder as the HTML file (or note the folder you put it in).
  2. Add <link rel="stylesheet" href="styles.css"> inside <head>, not in <body>. The path follows the same rules as an image path.
  3. Put one rule you cannot miss at the top, such as body { background: yellow; }, and reload. If the page turns yellow, the link works; now delete the test rule.
  4. If nothing changes, hold Shift while reloading (the browser may be showing an old cached copy), then check the href letter by letter against the file name, including capitals and the .css extension.

When the same property is set in all three places, the inline style attribute wins, then whichever of the <style> block and the linked file comes later in the head. See the specificity tab for the full order.

History and Versions

Getting Started

How CSS Got Here

Style sheets were proposed in 1994 by Håkon Wium Lie, working with Tim Berners-Lee at CERN, because web pages were starting to carry formatting that had no business in HTML. Every version since has added properties without changing the basic rule syntax, which is why a 1996 stylesheet still works.

VersionYearWhat it brought
CSS 11996The first W3C Recommendation: fonts, colors, text alignment, margins, borders, padding, and the cascade (which rule wins). Browser support was patchy for years.
CSS 21998Positioning (static, relative, absolute, fixed), z-index, media types for print and screen, richer selectors.
CSS 2.12011CSS 2 cleaned up to match what browsers actually implemented. For a long time this was the practical baseline.
CSS 31999 onwardNot one document but a set of modules that advance separately: selectors, colors with rgba and hsl, border-radius, shadows, gradients, transitions, animations, media queries for responsive design, web fonts.
Flexbox2012 (stable 2017)One-dimensional layout: a row or column of items that grow, shrink and align. Replaced floats for most layout work.
Grid2017Two-dimensional layout in rows and columns. Shipped in all major browsers within a few months of each other.
Modern CSS2017 onwardCustom properties (variables), clamp() and other math functions, container queries, nesting, and :has(). Much of what preprocessors were invented for is now built in.

There is no CSS 4. Each module has its own level number, so you will see Selectors Level 4 or Color Level 5, but the language as a whole is simply CSS.

Anatomy of a Rule

Rules and Selectors

One Rule

A style sheet contains one or more rules. A rule is a selector followed by a declaration block in braces. Each declaration is a property, a colon, a value, and a semicolon.

body {
    font-family: Tahoma, Arial, sans-serif;
    color: black;
    background: white;
    margin: 8px;
}
PartIn the exampleMeaning
SelectorbodyWhich elements the rule applies to
Declaration block{ ... }Everything between the braces
Declarationcolor: black;One property set to one value
PropertycolorWhat to change
ValueblackWhat to change it to

Reading Values

Lists
Shorthand

font-family: Tahoma, Arial, sans-serif is a fallback list: the browser uses the first font it has. End with a generic family such as sans-serif so there is always something.

Some properties bundle several: border: 5px solid red sets width, style and color at once, and margin: 8px sets all four sides. See the sizing tab.

Three syntax slips that silently break a rule. (1) A missing unit: font-size: 16; is invalid and ignored; write 16px. Only 0 and bare numbers for line-height, flex and opacity go without a unit. (2) A missing semicolon: color: red on one line followed by margin: 8px on the next is read as one garbled declaration, so both are dropped. End every declaration with ;. (3) Comments: CSS only knows /* like this */; a // line swallows the declaration after it. When a rule “does nothing”, inspect the element in the browser’s developer tools: an invalid declaration is shown struck through with a warning icon.

Selectors

Rules and Selectors

The Four Basic Selectors

SelectorCSSMatches this HTML
Tag nameh1 { color: red; }<h1>Today's Specials</h1>
Class.large { font-size: 16pt; }<p class="large">...</p> and any other element with that class
Tag and classp.large { ... }Only paragraphs with the class, not a <span class="large">
Element id#p20 { font-weight: bold; }<p id="p20">...</p>, the one element with that id

CSS and HTML

h1 { color: red; }
.large { font-size: 16pt; }
p.large { font-style: italic; }
#p20 { font-weight: bold; }

<h1>Today's Specials</h1>
<p class="large">A large paragraph</p>
<span class="large">A large span</span>
<p id="p20">The paragraph with id p20</p>

Result

Today's Specials

A large paragraph

A large span

The paragraph with id p20

Classes are the workhorse: an element can carry several (class="card large"), and one class can be used on any number of elements. An id must be unique on the page, so #p20 is for one specific thing, often a link target.

Combining Selectors

PatternExampleMeaning
Groupingh1, h2, h3 { ... }The same declarations for several selectors
Descendantnav a { ... }Links anywhere inside a <nav>
Childul > li { ... }List items that are direct children of the list
Adjacent siblingh2 + p { ... }A paragraph that comes immediately after a heading; handy for removing the gap under a title
Attributeinput[type="text"] { ... }Elements with that attribute value; a[href^="http"] matches external links
Two classes.card.large { ... }Elements that carry both classes (no space between them)
Universal* { ... }Every element; used for box-sizing resets

The space is a selector. nav a (with a space) means links inside a nav; nav.a would mean a nav that has the class a; p.large is a paragraph with the class; p .large is anything with the class inside a paragraph. Read a selector right to left: nav ul li a finds every link, then keeps those inside a list item, inside a list, inside a nav. Shorter selectors are easier to override later, so prefer .menu-link on the element to a long chain.

Pseudo-Classes

Rules and Selectors

Rules That Depend on State

A pseudo-class is added to a selector with a colon. The rule applies only while the element is in that state.

Pseudo-classApplies when
:hoverThe mouse is over the element. Tooltips, highlighted rows, button feedback.
:linkThe link has not been visited.
:visitedThe link has been visited.
:focusThe element has keyboard focus, such as a form field being typed in.
:activeThe element is being clicked.
:first-childThe element is the first child of its parent.
:nth-child(2n)Every second child; handy for striped table rows.

CSS and HTML

p:hover, a:hover {
    background-color: yellow;
}
a:link { color: blue; }
a:visited { color: green; }

<p>Rest the mouse on this paragraph.</p>
<a href="#">A link: blue until visited</a>

Result

Rest the mouse on this paragraph.

A link: blue until visited

Hover does not exist on a touch screen, so never make hover the only way to reach something. Order the link rules link, visited, hover, active so that later states override earlier ones.

Inheritance and Specificity

Rules and Selectors

Inheritance

InheritedSet it once on the parent
Not inheritedSet it on each element
  • font-family, font-size, font-weight
  • color
  • line-height, text-align
  • cursor

Set the font on body and every paragraph, heading and list inside it uses it unless a closer rule says otherwise.

  • border
  • background
  • margin, padding
  • width, height
  • display, position

Giving a <div> a border does not put a border on every paragraph inside it, which is what you want.

The pattern: properties about text inherit, properties about the box do not. Two surprises: links do not take the parent’s color, because the browser’s own a rule is more specific than inheritance, so style links directly; and form controls (button, input) do not inherit the font, so add button, input { font: inherit; } to your base stylesheet. The value inherit forces any property to copy its parent.

Multiple Rule Matches

When several rules match the same element, the most specific one wins. A rule naming a tag and a class beats a rule naming only the tag.

CSS and HTML

span.test { color: green; }
span { color: red; }

<span>Text1</span><br>
<span class="test">Text2</span>

Result

Text1
Text2
Specificity, lowest to highestExample
Tag selectorsspan
Class and pseudo-class selectors.test, a:hover
Id selectors#p20
Inline style attribute<p style="color: red">
!importantcolor: red !important; beats everything; avoid it

Ties are broken by order: the rule that appears later in the stylesheet wins. This is the “cascade” in Cascading Style Sheets.

How the browser decides, for one property on one element:

  1. Collect every declaration of that property from every rule whose selector matches the element, plus any inline style.
  2. If any of them carries !important, the important ones compete among themselves and the rest are ignored.
  3. Compare specificity. Count ids, then classes (and attributes and pseudo-classes), then tags. #p20 (1,0,0) beats .large.card (0,2,0), which beats div p span (0,0,3). No number of classes ever beats one id.
  4. If the specificity is equal, the declaration that appears last wins, counting the stylesheets in the order the head links them.
  5. If no rule sets the property at all, the element inherits it from its parent when the property inherits, otherwise it uses the browser default.

Specificity surprises. You write .active { color: red; } for the current menu link and nothing happens, because an earlier nav a { color: blue; } (one class-level step plus a tag) still outranks a lone class; the fix is to match it, nav a.active, not to add !important. An id in a selector locks that property away from every class that comes later, which is why most stylesheets avoid ids for styling. A rule that appears later does not win if it is less specific; order only breaks ties. When in doubt, the developer tools Styles panel lists every matching rule, struck through when it lost.

Color

Properties

color and background-color

Every color must ultimately become red, green and blue intensities from 0 to 255. There are four ways to write one:

FormExampleShows
Predefined namered (about 140 standard names)
Hexadecimal, two digits per channel#ff0000 = R ff, G 00, B 00
Decimal intensitiesrgb(255, 255, 0)
Percentage intensitiesrgb(80%, 80%, 100%)
With transparencyrgba(0, 0, 0, 0.5) (alpha 0 to 1)
Hue, saturation, lightnesshsl(210, 100%, 40%)

CSS and HTML

h1 { color: red; }
.box { background-color: rgb(80%, 80%, 100%); }

<h1>A red heading</h1>
<p class="box">A paragraph with a pale blue background</p>

Result

A red heading

A paragraph with a pale blue background

color is the text color and inherits; background-color paints the element’s box and does not.

The Box Model

Properties

Every Element Is a Box

Content sits inside padding, inside a border, inside margin. Padding and margin are transparent: the element’s background shows through the padding, and whatever is behind the element shows through the margin.

marginborderpaddingcontent(the element)widthheightTotal width =width+ left and right padding+ left and right border+ left and right marginMargin and paddingare transparent:the background showsthrough the padding;the page shows throughthe margin.

CSS and HTML

.box {
    width: 200px;
    padding: 20px;
    border: 5px solid #3E2E24;
    margin: 20px;
    background: #d0d0ff;
}

<div class="box">200px of content, 20px of padding, a 5px border and 20px of margin.</div>

Result

200px of content, 20px of padding, a 5px border and 20px of margin.

Total width = width + left and right padding + left and right border + left and right margin. The box above takes 200 + 40 + 10 + 40 = 290 pixels across. If that arithmetic annoys you, set box-sizing: border-box and width becomes the outer size of the border instead, which is what most people expect.

Two box-model mistakes that look like bugs. Margin collapse: when two blocks sit one above the other, their vertical margins do not add up, they overlap, so a paragraph with margin-bottom: 20px followed by one with margin-top: 20px has 20px between them, not 40; and a child’s top margin can poke out through its parent and move the parent instead. Horizontal margins never collapse. Forgetting box-sizing: with the default content-box, width: 100%; padding: 16px; makes an element 32px wider than its container and causes a sideways scrollbar; the * { box-sizing: border-box; } line in the template prevents it. Padding and borders never collapse, so when you need a guaranteed gap between two boxes, pad one of them.

Units

Properties

Absolute and Relative

AbsoluteA fixed physical size
RelativeScales with something else
UnitMeaning
2pxpixels
1mmmillimeters
2cmcentimeters
0.2ininches
3ptprinter points, 1/72 inch
UnitMeaning
2em2 times the element’s current font size
3rem3 times the root element’s font size
50%half of the parent’s size
100vwthe full width of the viewport
100vhthe full height of the viewport

Pixels are the everyday unit on screen; the physical units matter for print. em compounds (an em inside an em grows), rem does not, so rem is the safer choice for spacing and font sizes that should respect the user’s browser settings.

Which unit when: px for borders and anything that should stay hairline-thin (border: 1px solid); rem for font sizes, padding and margins (font-size: 1.25rem, 20px when the root is 16); em for things that should scale with the element’s own text, such as the padding inside a button; % for widths that follow the container (width: 50% is half the parent, whatever the screen); vh for a full-screen banner (min-height: 100vh). 0 needs no unit; every other length does.

Size, Padding, Margin and Border

Properties

The Properties

Element and spacing
Border
  • width, height override the element’s default size. A block is as wide as its container and as tall as its content until you say otherwise: width: 300px; or max-width: 600px; (which still lets it shrink on a phone).
  • padding-top, padding-right, padding-bottom, padding-left — space inside the border, between the border and the content. The background shows through it. padding-left: 12px; pushes the text 12px in from the left edge.
  • margin-top, margin-right, margin-bottom, margin-left — space outside the border, between this box and its neighbors. Transparent. margin-bottom: 1em; is the gap under a paragraph.
  • Padding or margin? If the gap should carry the element’s own background or border color, it is padding; if it should separate the element from the one next to it, it is margin.
  • border-bottom-color, border-bottom-style, border-bottom-width — one side at a time: border-bottom: 2px solid #ccc; is the usual underline for a heading or a table row.
  • border-left-..., border-right-..., border-top-... likewise
  • Styles: solid, dashed, dotted, double, none. A border with a width and a color but no style does not draw at all, because the default style is none; that is the usual reason a border “is missing”.
  • border-radius: 8px; rounds the corners; it works even when there is no visible border, to clip a background or an image.

Shorthand

Writing twelve border properties is tedious, so each family has a shorthand. Four values go clockwise from the top: top, right, bottom, left. Two values mean vertical then horizontal. One value means all four sides.

CSS and HTML

p {
    border: 5px solid red;
    padding: 10px 20px;      /* 10 top and bottom, 20 left and right */
    margin: 0 0 16px;        /* top, sides, bottom */
}

<p>A paragraph with a 5px solid red border, 10px vertical and 20px horizontal padding.</p>

Result

A paragraph with a 5px solid red border, 10px vertical and 20px horizontal padding.

ShorthandExpands to
margin: 8pxall four margins 8px
margin: 8px 16pxtop and bottom 8px, left and right 16px
margin: 0 autono vertical margin, centered horizontally (with a width)
padding: 1px 2px 3px 4pxtop 1, right 2, bottom 3, left 4
border: 5px solid redborder-width, border-style, border-color on all sides

How to center something, by what it is:

  1. Text or inline content inside a block: text-align: center; on the container. This centers the words, the images and the links in the line, not the block itself.
  2. A block with a known width: give it a width or max-width, then margin: 0 auto;. Without a width the block already fills its container, so there is nothing to center.
  3. Anything, horizontally and vertically: make the parent a flex container with display: flex; justify-content: center; align-items: center;, and give the parent a height if vertical centering is wanted.

The classic mistake is putting text-align: center on a block to center the block: the block stays put and only its text moves. The second is margin: auto on an inline element such as a span or an image; set display: block first.

Text, Backgrounds and Cursors

Properties

Fonts and Text

PropertyDoes
font-familyThe typeface, as a fallback list ending in a generic family
font-sizeSize in px, em, rem or pt
font-weightnormal, bold, or 100 to 900
font-stylenormal or italic
fontShorthand for all of the above: font: italic bold 16px/1.5 Arial, sans-serif
text-alignleft, center, right, justify. Set it on the block that holds the text; it aligns the lines inside, never the block itself
vertical-alignWhere inline content sits on the line, or within a table cell
text-decorationunderline, line-through, none (remove the underline on a link)
line-heightSpace between lines; a bare number such as 1.5 scales with the font

CSS and HTML

p {
    font-family: Georgia, serif;
    font-size: 18px;
    text-align: center;
}
.strike { text-decoration: line-through; }

<p>Centered Georgia at 18px, with <span class="strike">one struck word</span>.</p>

Result

Centered Georgia at 18px, with one struck word.

Backgrounds and Cursors

PropertyDoes
background-colorA solid color behind the element
background-imageurl("clouds.gif"), an image behind the element
background-repeatrepeat tiles it (the default); no-repeat shows it once
background-sizecover fills the box, contain fits inside it
cursorThe mouse pointer over the element: pointer for clickable things, help for a question mark, not-allowed

CSS and HTML

.tip {
    cursor: help;
    background-color: #fff3b0;
    padding: 4px 8px;
}

<p>Rest the mouse on <span class="tip">this phrase</span> to see the help cursor.</p>

Result

Rest the mouse on this phrase to see the help cursor.

Display and Visibility

Layout

display

ValueEffect
display: none;The element is not displayed and takes no space in the layout.
display: inline;Treated as an inline element: flows with text, no line break, width and height ignored.
display: block;Treated as a block element: starts on a new line, takes the full width, accepts width and height.
display: inline-block;Flows with text but accepts width, height and vertical padding.
display: flex;The element becomes a flex container; its children line up in a row or column.
display: grid;The element becomes a grid container; its children fill rows and columns.

CSS and HTML

.a { display: inline; background: #d0d0ff; }
.b { display: block; background: #ffd0d0; }
.c { display: none; }

<span class="a">inline</span> <span class="a">inline</span>
<span class="b">block takes the whole line</span>
<span class="c">this one is display: none</span>
<span class="a">inline again</span>

Result

inline inline block takes the whole line this one is display: none inline again

The mistake that costs beginners the most time: width, height, margin-top and margin-bottom are ignored on an inline element. A span, an a or an img given width: 200px stays exactly as it was. Switch it to display: inline-block (keeps it in the line of text) or display: block (its own line) and the size applies. display: none also hides the element from screen readers and from the tab key, so use it for things that truly do not exist right now, not for things that are merely off screen.

visibility

visibility: hidden;
visibility: visible;

The element is hidden but its space is still allocated. The layout does not shift, which makes it useful for things that appear and disappear in place.

The default. Compare with display: none, which removes the element from the layout entirely and lets everything else close up.

CSS and HTML

.gone { visibility: hidden; }

<p>Before <span class="gone">[this span is hidden but still takes space]</span> after.</p>

Result

Before [this span is hidden but still takes space] after.

Position

Layout

The Four Values

ValuePositioned
position: static;The default. In the normal document flow; top, left and the others are ignored.
position: relative;Relative to its own default position, by top, right, bottom and left. The space it would have taken stays reserved.
position: absolute;Relative to the nearest ancestor that is itself positioned (anything other than static). Removed from the flow; other content closes up.
position: fixed;At a fixed spot on the screen, measured from the viewport; stays put when the page scrolls. (0, 0) is the top left corner.
position: sticky;Flows normally until the page scrolls it to the given offset, then sticks there. Newer than the lecture; used for headings that stay visible.

CSS and HTML

.parent {
    position: relative;
    height: 130px;
    padding: 10px;
    background: #f2eadc;
}
.child {
    position: absolute;
    bottom: 10px;
    right: 10px;
    padding: 6px 10px;
    background: #d0d0ff;
}
.nudged {
    position: relative;
    left: 30px;
}

<div class="parent">
  <p class="nudged">Nudged 30px right, space kept.</p>
  <div class="child">Absolute: bottom right of the parent</div>
</div>

Result

Nudged 30px right, space kept.

Absolute: bottom right of the parent

The usual recipe: give the container position: relative so that absolute children measure from it rather than from the page. A fixed element cannot be shown inside this demo box because it would pin itself to your screen.

Three position surprises. An absolute element with no positioned ancestor measures from the whole page, so it lands at the top-left corner of the document, not of the box you meant: add position: relative to that box. z-index (which box is on top) only works on elements whose position is not static. And top, left and friends do nothing at all on the default static; if a nudge is ignored, check that position is set.

Flexbox and Grid

Layout

Two Layout Systems

FlexboxOne dimension
GridTwo dimensions

display: flex lays out a row or a column of items. Items flex to fill extra space and shrink to fit smaller spaces, and they align easily even when they are different sizes. Use it for menus, toolbars, and anything that is a line of things.

display: grid lays out rows and columns at once. You name the tracks and place items in them. Use it for page layouts, galleries, and anything that is a table of things without being tabular data.

Both are the key to handling different window and display sizes: divide the available space among a bunch of elements, and let the browser do the arithmetic.

How to make a layout respond to the screen:

  1. Make sure the HTML head has <meta name="viewport" content="width=device-width, initial-scale=1.0">; without it a phone pretends to be a 980px desktop and shrinks everything.
  2. Write the narrow layout first, with no columns: one column flows naturally on a phone with nothing to do.
  3. Add the wider layout inside a media query, a block of rules that applies only when the window is at least a certain width.
  4. Use flexible units inside it: fr, % and max-width rather than fixed pixel widths, and img { max-width: 100%; } so pictures never overflow.
.layout { display: grid; grid-template-columns: 1fr; gap: 16px; }

@media (min-width: 700px) {
    .layout { grid-template-columns: 1fr 2fr; }
}

On a phone the sidebar and the content stack; once the window is 700px or wider, the same two elements sit side by side, one third and two thirds. Resize the browser window to watch the switch. The common mistake is writing the desktop layout first and then fighting it with a max-width query; narrow first is less code.

Flexbox

CSS and HTML

.row {
    display: flex;
    gap: 10px;
}
.row > div {
    flex: 1;             /* share the space equally */
    padding: 10px;
    background: #d0d0ff;
    text-align: center;
}
.row > .wide { flex: 2; }

<div class="row">
  <div>1</div>
  <div class="wide">2 (twice as wide)</div>
  <div>3</div>
</div>

Result

1
2 (twice as wide)
3
PropertyOnDoes
flex-directioncontainerrow (default) or column
justify-contentcontainerSpacing along the main axis: center, space-between
align-itemscontainerAlignment across the axis: center, stretch
gapcontainerSpace between items
flexitemHow much of the free space the item takes
flex-wrapcontainerwrap lets items drop to a new line

Grid

CSS and HTML

.grid {
    display: grid;
    grid-template-columns: 1fr 2fr;
    grid-template-rows: auto auto;
    gap: 10px;
}
.grid > div {
    padding: 10px;
    background: #ffd0d0;
}
.grid > .full { grid-column: 1 / -1; }

<div class="grid">
  <div class="full">Header across both columns</div>
  <div>Sidebar (1fr)</div>
  <div>Main content (2fr)</div>
</div>

Result

Header across both columns
Sidebar (1fr)
Main content (2fr)
PropertyDoes
grid-template-columnsThe column tracks: 200px 1fr, repeat(3, 1fr)
grid-template-rowsThe row tracks
gapSpace between cells
grid-column, grid-rowWhere an item sits and how many tracks it spans: 1 / 3 or span 2
frA share of the free space: 1fr 2fr is one third and two thirds

Worked Example

The lecture’s full example, rendered live

CSS and HTML

Three rules and a short page. The body rule sets the base font and an 8px margin, h1 shrinks the headings and underlines them, and .shaded tints one section.

styles.css

body {
  font-family: Tahoma, Arial, sans-serif;
  font-size: 13px;
  color: black;
  background: white;
  margin: 8px;
}
h1 {
  font-size: 19px;
  margin-top: 0px;
  margin-bottom: 5px;
  border-bottom: 1px solid black;
}
.shaded {
  background: #d0d0ff;
}

page.html

<body>
  <h1>First Section Heading</h1>
  <p>
    Here is the first paragraph, containing
    text that really doesn't have any use
    or meaning; it just prattles on and on,
    with no end whatsoever, no point to
    make, really no purpose for existence
    at all.
  </p>
  <div class="shaded">
    <h1>Another Section Heading</h1>
    <p>
      Another paragraph.
    </p>
  </div>
</body>

Output

Both headings get the 19px size and the rule beneath, because the h1 selector matches both. Only the second section is shaded, because only it has the class.

First Section Heading

Here is the first paragraph, containing text that really doesn't have any use or meaning; it just prattles on and on, with no end whatsoever, no point to make, really no purpose for existence at all.

Another Section Heading

Another paragraph.

CSS in the Real World

Preprocessors
Composition is the hard part

Tools such as Less and Sass add variables, functions and nesting to help maintain large collections of style sheets, and apply scoping through naming conventions. Modern CSS has absorbed much of this: custom properties, calc(), and native nesting.

With many stylesheets it can be really hard to figure out which rule from which file is messing things up. The browser’s developer tools (right-click, Inspect) show every rule that matches an element and which one won. Learn that panel early.