Cascading Style Sheets (CSS) Knowledge

Kip Landergren

(Updated: )

My Cascading Style Sheets (CSS) knowledge base explaining selectors, rules, the box model, and other language components.

Contents

Forward

This is an evolving document: I make updates as I learn, build and understand more. All errors are my own!

In particular, I recommend reading Håkon Wium Lie’s PhD Thesis: Cascading Style Sheets from which this document’s structure and content largely follows. His paper contains rich insight on CSS during the early days of the web and provides a view into the care and skill employed getting CSS released. This website would not exist in its current form without it!

Overview

Cascading Style Sheets (CSS) is a language for describing the rendering of structured documents like HTML, XML, and SVG.

Style Sheets and the Cascade

A style sheet is a collection of rules that associate stylistic properties and values with a structured document’s elements. The term originates in print media where a style sheet ensured consistent presentation, spelling, and punctuation when laying out content.

An example CSS style sheet:

/* match all `h1` elements */
h1 {
  /* set their `color` property to `green` */
  color: green;
}

Cascading refers to process by which multiple style sheets—possibly from the content author, the browser, or the user—are combined to determine a structured document’s style and layout.

This cascading behavior addresses the dynamic between:

CSS Language Management

The language is managed by the CSS Working Group (CSSWG), a working group created by the World Wide Web Consortium (W3C), and defined through a series of specifications written by the CSSWG and recommended by the W3C.

Specifications mature through the W3C Process but have a coordination problem:

Representatives from browser vendors feature heavily in the CSSWG in part to address this issue. Additionally, the CSSWG publishes “Snapshot” documents that seek to communicate to implementors what is considered the current state of “stable CSS”, regardless of specification W3C recommendation status.

Each major browser engine ships with its own implementation of CSS. These versions provide varying support for CSS specification features, which, along with bugs and divergent interpretations of the specification, creates discrepancies between how structured content is rendered in one browser vs. another.

“CSS3” and CSS Modules

The first and second CSS specifications, CSS1 and CSS2, were monolothic documents. CSS3 was different: it was not a single document but the start of a modular approach where the language was divided into functional areas each with their own specification.

I think of CSS3 as a demarcation point for the shift to a module-based specification strategy, rather than a single fixed set of criteria or specification.

Of note:

A non-exhaustive list of additional modules introduced in CSS3 are:

Core Idea

CSS should provide:

language for styling structured documents on the web.

Strive to provide functionality such that anything laid out in print can be laid out using CSS. Embrace non-programmer CSS authors and transfer conventions from traditional typographic and print media.

Provide a clear model for style rule resolution such that both authors’ content displays as they intend and users’ view of that content accomodates their preferences.

Lay out content using a well-defined visual format model—the box model—that scales with devices, produces consistent results across implementations, and degrades gracefully.

The Language

CSS is a declarative, non-Turing-complete language that aims to be simple and suitable for non-programmers to use.

Goals and Requirements

Syntax

        h1       {
/* \_SELECTOR_/                                                 */
         color           :           green             ;
/* \_PROPERTY NAME_/ \_COLON_/ \_PROPERY VALUE_/ \_SEMI COLON_/ */
/* \_______________________DECLARATION________________________/ */
                 }
/*              \___DECLARATION BLOCK (within matching {})____/ */
/* \_____________________RULE SET (RULE)______________________/ */

Components

Selectors

Selectors describe the conditions under which to match elements or display objects of a structured document.

Simple Selectors

Simple selectors may match elements using type, attributes, and attribute values:

h1 {
  color: green;    
}
id Selectors
#id-name {
  background-color: red;
}
Contextual Selectors

Contextual selectors may match elements based on their position in the structured document, using a composition of multiple simple selectors and operators:

/* match an `h2`,
   contained within a `section`,
   contained within an `article` */
article section h2 {
  border-top: 3px solid black;
}
Pseudo-Element Selectors

Pseudo-element selectors may match display objects—like the first line of a rendered paragraph or the first letter of a line—rather than structural elements:

/* match the _display object_ containing the first letter of every `p`
   element's content */
p::first-letter {
  text-transform: uppercase;
}

Note: the use of :: to prefix pseudo-elements was introduced in CSS3 as a convention to distinguish between pseudo-elements and pseudo-class selectors.

Pseudo-Class Selectors

Pseudo-class selectors may match elements based on external state, like whether a user has already visited a link:

/* match any `a` element that has already been visited by the user */
a:visited {
  border: dashed purple;
}

Properties

Properties are identifiers for mutable aspects of an element’s display format (which may be visual, aural, tactile, or something else), like:

and are applied to the elements matching the selectors of their contained rule set.

Example:

/* set multiple properties in a single rule set  */
div {
  background-color: #f9f9f9;
  color: black;
}

Shorthand properties are ones whose value assigns multiple properties via a terser value syntax. This terser syntax is intended to improve readability and help translate existing conventions from typography and print industries to CSS.

/* longhand  */
div {
  border-top: 1px;
  border-right: 2px;
  border-bottom: 3px;
  border-left: 4px;
}

/* shorthand (equivalent)  */
div {
  border-width: 1px 2px 3px 4px;
}

Values and Units

TYPE DEFINITION EXAMPLE
keywords words with special meaning, no quotes needed border-collapse: inherit;
strings any text content: '→';
numbers (without units) integers or reals border: 0;
numbers (with units) integers or reals with units padding-left: 1.25rem;
percentages amount relative to another value width: 50%;
functions the return value of calling a built-in CSS function width: calc(50% + 20px);

Units of length are broken down into:

/* absolute length unit `cm`  */
p {
  height: 1cm;
}

/* relative length unit `em`, which is in relation to the value of font-size */
p {
  height: 1.5em;
}

Value Propagation Mechanism

Three short-circuiting checks, in order:

The Cascade

Three checks, in order:

Inheritance

CSS designates certain properties as inherited: an inherited property on a child element (that is not otherwise set) will take the same value of that property as on its parent.

Additionally, properties may be set with the value inherit, which instructs CSS to explicitly assign the parent’s value for that property to the child.

Initial Value

Every CSS property has an initial value.

Formatting Model

The three main axes CSS compromises between are:

The Box Model

Documents are laid out as a series of nested boxes conforming to the following diagram:

The CSS box model, showing nested rectangular bands starting with 'margin', 'border', and 'padding' around a central rectangular 'content' area

Positioning Boxes

Block boxes:

Inline boxes:

Additional positioning mechanisms include:

Flexbox

display: flex; is a means of controlling the layout of items along a single dimension of a container.

(Note: A second dimension is partially configurable via flex-wrap: wrap;, in which case a row or column or elements “wraps” into the next zone. Check if CSS Grid may be more suitable.)

two examples of flex-direction, row and column

Flex child item position and behavior are primarily controlled by two groups of properties:

and:

I have found the MDN article Typical Use Cases of Flexbox to be helpful understanding Flexbox’s application and its distinct usage from Grid.

Important: there are two CSS Modules to be aware of:

It is my understanding that “CSS Box Alignment Module Level 3” will eventually supercede “CSS Flexible Box Layout Module Level 1”. You may see properties from Box Alignment show up in browser support for flexbox / flex items, like gap, but be aware of the two distinct specifications.

Example: justify-content
justify-content: flex-start;
justify-content: flex-end;
justify-content: center;
justify-content: space-between;
justify-content: space-around;
justify-content: space-evenly;

Authoring and Using CSS

Browser Reset

Browsers come preloaded with styles that some CSS frameworks will “reset” to some baseline value that brings all browsers into uniformity.

Resources