Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / CSS

@import — loading another stylesheet

The @import rule loads a stylesheet from a URL and can condition it with a cascade layer, support query, or media query.

Version: CSS modules; structured CSSWG indexes reconciled with pinned MDN BCD; Chromium 152 scope gate, per-example verification still required

Syntax

@import [ <string> | <url> ]
        [ layer | layer(<layer-name>) ]?
        [ supports( [ <supports-condition> | <declaration> ] ) ]?
        <media-query-list>? ;

@import <url-or-string> [layer | layer(<name>)]? [supports(<condition>)]? <media-query-list>?; is a statement rule terminated by a semicolon. Imported rules behave as though they occurred at the import position. layer places them in an anonymous or named cascade layer, supports() can avoid fetching when its condition is false, and a media list limits application.

An @import must precede ordinary style rules and most other rules; an encoding declaration and permitted layer-order statements may come first. An import inside a block or after a disallowed rule is ignored. A relative URL resolves against the importing stylesheet’s URL, not directly against the HTML document.

Each import can extend the fetch dependency chain and delay available styles, so production builds often prefer <link> or bundling. A failed import does not discard the rest of the importing sheet. The example loads a Blob stylesheet that imports a second data: sheet; after load it reads one custom value from the import and another from the local rule.

Examples

const css = '@import url("data:text/css,.probe%7B--from-import%3Aloaded%7D"); .probe { --local: ready; }';
const url = URL.createObjectURL(new Blob([css], {type: 'text/css'}));
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = url;
document.head.append(link);
await new Promise((resolve, reject) => { link.onload = resolve; link.onerror = reject; });
const probe = document.createElement('div');
probe.className = 'probe';
document.body.append(probe);
const computed = getComputedStyle(probe);
console.log('import=' + computed.getPropertyValue('--from-import').trim() + '; local=' + computed.getPropertyValue('--local').trim());
URL.revokeObjectURL(url);

Result

import=loaded; local=ready

The @import rule loads a stylesheet from a URL and can condition it with a cascade layer, support query, or media query.

Sources