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
- Overview
- Core Idea
- The Language
- Authoring and Using CSS
- Resources
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:
- an author’s desire to layout their content in a specific way
- a user’s desire to consume content in a format best for them
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:
- a specification’s stability increases when it has more implementations (e.g. multiple browsers supporting its features)
- implementations prefer to build support when a specification is stable
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:
- CSS2 succeeded CSS1 in totality, and has been updated (as of May 2021) since as CSS2.2
- CSS3 does not succeed CSS2.2 in totality: CSS3 contains CSS2.2 as a module
A non-exhaustive list of additional modules introduced in CSS3 are:
Core Idea
CSS should provide:
- an easy-to-understand
- declarative
- selector-based
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
- forward compatibility: old CSS engines should be able to parse new CSS
- keep structured content (HTML, XML, SVG) focused on semantics, not style
- provide defined mechanism for both content authors and users to control style
- keep language simple, and be suitable for non-programmers
- keep content transformation to a minimum; pseudo-elements are the exception
- support progressive rendering
- allow CSS to work with any structured markup
- be able to target multiple devices for content presentation
- be declarative, emphasizing selectors over expressions
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:
border
color
background-color
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 units, which reproduce their length on the user’s screen
- relative units, which are affected by another value
/* 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:
- cascade: was the property set with a value?
- inheritance: does the parent element property yield a value?
- initial value: use the CSS-set initial value for the property
The Cascade
Three checks, in order:
- origin: prefer, in order, the rules set by:
- the author
- the user
- the browser and take into account use of
!important
to override.
- specificity: which rule has the higher specificity calculation?
- order: whichever rules were processed later (e.g. below other rules in a single style sheet) win.
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:
- simplicity vs. richness
- pixel-perfection vs. device outreach
- short-term goals vs. long-term goals
The Box Model
Documents are laid out as a series of nested boxes conforming to the following diagram:
Positioning Boxes
Block boxes:
- will generate line breaks
- has its outline determined by the outer edge of the margin box
- in the horizontal direction: will “push” other elements aside
- in the vertical direction: will “collapse” adjacent margin values
Inline boxes:
- will not generate line breaks
- in the vertical direction: margin, border, and padding are visible but have no layout effect
- in the horizontal direction: will “push” other elements aside
Additional positioning mechanisms include:
- floating, allowing other content to flow along its side
- absolute, where elements are taken completely out of page flow and positioned absolutely relative to one another
- fixed, which is similar to absolute positioning but relative to the viewport
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.)
- main axis is in the direction of the container’s flow
- cross axis is perpendicular to the direction of the container’s flow
Flex child item position and behavior are primarily controlled by two groups of properties:
justify-content
, which positions items along the main axisalign-items
, which positions items along the cross axis
and:
flex-basis
, which controls item size along the main axisflex-grow
, which controls item growth along the main axisflex-shrink
, which controls item shrinkage along the main axis
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:
- CSS Flexible Box Layout Module Level 1
- CSS Box Alignment Module Level 3
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
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
- CSS Working Group homepage | W3C
- CSS Working Group Editor Drafts | GitHub repository
- Latest CSS Snapshot | W3C
- PhD Thesis: Cascading Style Sheets | Håkon Wium Lie
- How to Read W3C Specs | J. David Eisenberg
- CSS Writing Modes | Jen Simmons
- What is the difference between phrasing content and flow content? | Stack Overflow