Skip to content
Tutorials Center
My learning

Topics

Lesson 120 of 139 ยท Best Practices

CSS At-rules Overview

A map of every CSS at-rule, from @import, @media and @layer to @property, @counter-style and @starting-style: what each does, how it's written, and where to learn more.

Most of a stylesheet is made of style rules: a selector and a block of declarations. Everything else starts with an @ sign. These at-rules load other files, apply styles only under certain conditions, organize the cascade, and define named things such as fonts, animations and counter styles that the rest of your CSS can use.

You've met most of them already, scattered through this course: @media in responsive design, @keyframes in animation, @layer in the cascade chapter. This lesson puts them all on one map. You'll learn the three shapes an at-rule can take, which rules must come first, how browsers treat at-rules they don't know, and what every current at-rule does, with a link to the lesson that covers it in depth.

Three shapes of at-rule

Every at-rule starts with @ and a name. After that, it takes one of three forms:

CSS
/* 1. A statement: ends with a semicolon, no block */
@import url("reset.css") layer(reset);

/* 2. A conditional or grouping rule: a block of ordinary style rules */
@media (width >= 50rem) {
  .sidebar { display: block; }
}

/* 3. A descriptor block: a block of descriptors that define something */
@font-face {
  font-family: "Brand Sans";
  src: url("/fonts/brand-sans.woff2") format("woff2");
  font-display: swap;
}

The third shape deserves a closer look. Inside @font-face, font-family and src look like properties, but they're descriptors: settings that belong to the at-rule, not to any element. That's why @font-face has descriptors you'll never see in a style rule (like src and unicode-range), and why writing color: red inside it does nothing. The same is true for @property, @counter-style, @page and the other "definition" rules.

Some at-rules can be written in more than one shape. @layer reset, base, components; is a statement that declares an order, while @layer base { โ€ฆ } is a block that adds rules to a layer.

Rules that must come first

Three at-rules only work at the very top of a stylesheet, in this order:

  1. @charset declares the file's character encoding, as in @charset "UTF-8";. It must be the very first thing in the file, with not even a space before it. Today you almost never need it: serve your CSS as UTF-8 (which is the default) and the browser figures it out.
  2. @import pulls in another stylesheet. It can add a layer, a media query or a supports() condition: @import url("print.css") print;. Every @import must come before all other rules except @charset and @layer statements. An @import that appears later is ignored, silently.
  3. @namespace declares XML namespaces for selectors. It must follow any @charset and @import rules.

The silent failure of a late @import catches people out, so here it is in action. Both imports below load a tiny stylesheet written inline as a data: URL; only the first one counts:

A late @import is ignored

(%23 is an encoded #, which is needed inside a URL.) Beyond ordering, @import has a performance cost: the browser only discovers the imported file after downloading the first one, so the requests happen one after another. CSS Performance explains why <link> elements or a build step are usually better.

@namespace in practice

You'll rarely need @namespace in HTML pages, but it shows up when styling inline SVG or XML documents. Without any declarations, a type selector like a matches elements of that name in every namespace, so it hits both HTML links and SVG links. A prefix lets you target just one:

Selecting SVG elements with @namespace

The svg| prefix is declared by the @namespace rule. Both links are bold, because the plain a selector matches them both, but only the SVG one is magenta.

Conditional rules

Conditional at-rules wrap ordinary style rules and apply them only while a condition is true:

  • @media tests the device and viewport: width, orientation, prefers-color-scheme, prefers-reduced-motion, print and more.
  • @supports tests whether the browser understands a property, value or selector: @supports (display: grid) or @supports selector(:has(a)).
  • @container tests the size (or custom-property style) of an ancestor container instead of the whole viewport.

They nest inside each other, and with CSS nesting they can sit right inside a style rule. The panel below uses only @supports. Each row starts as "no" and flips to "yes" when your browser supports that feature:

What does this browser support?

Rules that organize the cascade

Two at-rules don't test anything. Instead, they change how rules compete:

  • @layer puts rules into named layers whose order beats specificity. A statement such as @layer reset, base, components, utilities; at the top of your CSS fixes the order once.
  • @scope limits rules to a subtree of the page, with an optional lower boundary: @scope (.card) to (.card-content) { โ€ฆ }. Inside it, the nearer scope root wins ties.

Both are block rules that contain ordinary style rules, so they can also hold @media and other conditionals.

Rules that define named things

The largest group uses descriptor blocks to define something that you then refer to by name elsewhere:

  • @font-face defines a font family from files. You use it through font-family.
  • @font-feature-values gives friendly names to a font's alternate glyph sets, so font-variant-alternates: swash(fancy) can mean "swash set 1" in one font and "set 3" in another.
  • @font-palette-values defines a custom palette for a color font, which you apply with font-palette.
  • @keyframes defines a named animation sequence for animation-name.
  • @property registers a custom property with a type, an initial value and inheritance, which lets it animate.
  • @counter-style defines a numbering style that works in list-style-type and counter().
  • @position-try defines a named fallback position for anchor-positioned elements.
  • @page sets the page size and margins when printing.
  • @view-transition opts a site into animated transitions between its pages.
  • @color-profile names an ICC color profile for the color() function. It's specified, but no major browser supports it yet.

Named definitions are where at-rules combine nicely. In the next demo, @property makes --count an animatable integer, @keyframes animates it from 0 to 100, and a @counter-style displays it with leading zeros:

@property, @keyframes and @counter-style together

Notice the last rule: a conditional at-rule (@media) turns the animation off for people who ask for less motion, which Motion and Performance covers in detail.

@starting-style: styles for the first frame

@starting-style is a block rule with a narrow job. Transitions only run when a value changes, so an element that has just been added to the page, or just switched from display: none, normally appears at once. Rules inside @starting-style give the element a "before" state for its very first style calculation, so it can transition in:

Entry transitions with @starting-style

Each new task fades and slides in, with no class toggling or requestAnimationFrame tricks. Opacity and Visibility and Dropdowns use the same rule to animate elements that start hidden.

An obsolete at-rule: @document

You may find @document in older references. It was designed to apply a block of rules only on certain documents, chosen by their address:

CSS
@document url("https://example.com/"), url-prefix("https://example.com/blog/"), domain("example.org"), regexp("https://example\\.com/(a|b)") {
  body { background: #fff8e1; }
}

The condition functions were url() (an exact address), url-prefix() (an address that starts with a string), domain() (a host and its subdomains), media-document() and regexp() (a pattern that must match the whole address). The idea was mostly for user stylesheets and browser extensions that restyle other people's sites.

It never became part of what works on the web. Firefox supported a prefixed @-moz-document, which was later limited to user stylesheets only, and other browsers never shipped it. It was dropped from the draft specification, so a normal website cannot use it. If you need page-specific CSS, add a class or data- attribute to <html> or <body> on that page (or load a page-specific stylesheet) and write ordinary selectors such as .page-blog .card.

How browsers handle unknown at-rules

CSS is designed to move forward without breaking old browsers. When a browser meets an at-rule it doesn't recognize, it skips the entire rule (up to the next semicolon for a statement, or the end of its block) and carries on with the rest of the stylesheet. Nothing else is affected.

That makes new at-rules safe to add. A browser without @scope support ignores the scoped block, so put a simpler fallback in your normal rules first. Inside a known at-rule, the same applies to unknown descriptors: an @font-face with a misspelled descriptor still loads its font, minus that one setting.

The same tolerance means typos fail silently. @media (min-width 600px), with a missing colon, is a valid-looking rule whose condition is never true. When a block of rules seems to be ignored, check the at-rule first in your browser's DevTools.

New at-rules are still being added. Proposals such as @function (custom functions written in CSS) and @custom-media (named media queries) are starting to appear in browsers. Treat anything very new as an extra and check a current compatibility table before depending on it.

The complete map

At-rule Shape What it does Learn more
@charset statement Declares the stylesheet's encoding (first byte of the file) Syntax
@import statement Loads another stylesheet, optionally into a layer or under a condition Adding CSS
@namespace statement Declares XML namespace prefixes for selectors This lesson
@media conditional Applies rules for certain devices and viewport features Media Queries
@supports conditional Applies rules when a feature is supported Feature Queries
@container conditional Applies rules based on an ancestor container Container Queries
@layer statement or block Declares cascade layers and adds rules to them Cascade Layers
@scope block Limits rules to part of the page Scope
@starting-style block Sets "before" styles for entry transitions Transitions
@font-face descriptors Defines a web font Web Fonts
@font-feature-values descriptors Names a font's alternate glyph sets Fonts
@font-palette-values descriptors Defines a palette for a color font Web Fonts
@keyframes keyframe block Defines an animation Animations
@property descriptors Registers a typed custom property Custom Properties
@counter-style descriptors Defines a numbering style Counters
@page descriptors Sets printed page size and margins Print Styles
@position-try descriptors Defines a fallback position for anchored elements Anchor Positioning
@view-transition descriptors Opts in to cross-document view transitions View Transitions
@color-profile descriptors Names an ICC color profile (not yet supported) Modern Colors
@document conditional Applied rules by document address (obsolete: not available to websites) This lesson

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A stylesheet starts with body { margin: 0; } and then @import url("theme.css");. What happens?

    @import must come before every other rule except @charset and @layer statements. A late @import is silently dropped.
  2. 2. Why does color: red inside @font-face have no effect?

    Definition at-rules like @font-face, @property and @counter-style accept only their own descriptors. Unknown ones are ignored.
  3. 3. What does a browser do with an at-rule it doesn't recognize?

    Unknown at-rules are skipped up to their semicolon or the end of their block, which is why new at-rules are safe to add.
  4. 4. Which at-rule lets an element added to the page transition in from an initial state?

    @starting-style gives an element its "before" styles for its first style calculation, so normal transitions can run on entry.
  5. 5. Which of these at-rules is a conditional rule?

    @container, like @media and @supports, applies its rules only while its condition is true. @layer organizes the cascade, and the other two define things.

Summary

  • At-rules start with @ and come in three shapes: statements ending in ;, blocks of style rules, and blocks of descriptors that define something.
  • @charset, @import and @namespace must come first, in that order; a late @import is silently ignored.
  • @media, @supports and @container apply rules conditionally; @layer and @scope organize the cascade.
  • @font-face, @keyframes, @property, @counter-style, @position-try, @page and friends define named things you use elsewhere.
  • @starting-style provides first-frame styles so elements can transition in.
  • Browsers skip at-rules they don't understand, which makes new ones safe to add but lets typos fail silently.

Next: Project: Profile Card, where you will put the box model, typography and shadows together in your first complete CSS project.