Skip to main content
The CSS engine transforms stylesheets into computed styles for each element. This involves tokenization, parsing CSS syntax, matching selectors to elements, resolving the cascade, and computing final style values.

CSS tokenizer and parser

CSS parsing begins with tokenization, converting the raw stylesheet text into tokens, followed by parsing those tokens according to CSS grammar rules.

Tokenization process

The CSS tokenizer breaks the input stream into meaningful tokens:
1

Read input stream

Process the stylesheet character by character, handling Unicode and escape sequences.
2

Recognize token patterns

Identify different token types based on character patterns:
  • Identifiers (property names, selector names)
  • Functions (e.g., rgb(), calc())
  • Strings (quoted values)
  • Numbers and dimensions (e.g., 10px, 1.5em)
  • Delimiters (:, ;, {, }, ,)
  • Operators (+, -, *, /)
  • Hash tokens (#id, #color)
  • At-keywords (@media, @keyframes)
3

Handle whitespace and comments

CSS comments (/* ... */) are discarded during tokenization. Whitespace is significant in some contexts (e.g., selector combinators) but not others.
4

Emit tokens

Send tokens to the parser for syntax analysis and structure building.

Grammar implementation

The CSS parser constructs a structured representation (CSSOM - CSS Object Model) by following CSS grammar rules.
CSS uses a relatively simple grammar compared to programming languages, but it must handle error recovery gracefully since invalid CSS rules should be ignored rather than causing parsing to fail.
A stylesheet consists of a list of rules and at-rules:
At-rules include @import, @media, @keyframes, @font-face, etc.
Each rule consists of selectors and a declaration block:
Example: h1, h2 { color: blue; font-size: 2em; }
Selectors are composed of simple selectors and combinators:
Examples:
  • div.container > p (descendant and child combinators)
  • a:hover::before (pseudo-class and pseudo-element)
  • input[type="text"] (attribute selector)
Declarations consist of property-value pairs:
The value can be keywords, numbers, colors, functions, or combinations.
CSS parsers must implement error recovery by skipping invalid rules and continuing to parse the rest of the stylesheet. A single syntax error should not prevent other valid rules from being applied.

Media query evaluation

Media queries allow conditional application of styles based on device characteristics.
Basic media types target different output devices:
Media queries are evaluated at stylesheet parse time and whenever the relevant device characteristics change (viewport resize, orientation change, etc.). The browser maintains an active set of matching media queries to determine which rules apply.
You now understand the CSS engine’s tokenization and parsing phases. Next, we’ll explore how parsed CSS rules are matched to HTML elements through selector matching.