Reference/At-rules/@import

김동현·2026년 3월 28일

mdn 학습 번역 - CSS

목록 보기
177/190

@import

Baseline | Widely available *

Chrome, Edge, Firefox, Safari에서 지원돼요.

이 기능은 잘 확립되어 있고 많은 기기와 브라우저 버전에서 작동해요. 2015년 7월부터 모든 브라우저에서 사용 가능했어요.

* 이 기능의 일부 부분은 지원 수준이 다를 수 있어요.

@import CSS at-rule은 다른 유효한 스타일시트에서 스타일 규칙을 가져오는 데 사용돼요. @import 규칙은 스타일시트의 맨 위에, 다른 at-rule(@charset@layer는 제외)과 스타일 선언보다 앞에 정의되어야 해요. 그렇지 않으면 무시될 거예요.

구문 (Syntax)

@import url;
@import url layer;
@import url layer(layer-name);
@import url layer(layer-name) supports(supports-condition);
@import url layer(layer-name) supports(supports-condition) list-of-media-queries;
@import url layer(layer-name) list-of-media-queries;
@import url supports(supports-condition);
@import url supports(supports-condition) list-of-media-queries;
@import url list-of-media-queries;

여기서 각 항목은 이런 의미예요.

url

가져올 리소스의 위치를 나타내는 <string>이나 <url> 타입이에요. 주소는 절대 경로일 수도 있고 상대 경로일 수도 있습니다.

list-of-media-queries

쉼표로 구분된 미디어 쿼리 목록이에요. 연결된 URL에 정의된 CSS 규칙을 적용하기 위한 미디어 관련 조건을 지정하죠. 만약 브라우저가 이 쿼리 중 어느 하나라도 지원하지 않으면, 연결된 리소스를 아예 로드하지 않아요.

layer-name

연결된 리소스의 내용을 불러올 캐스케이드 레이어(cascade layer)의 이름이에요. 더 자세한 내용은 layer() 문서를 참고해 보세요.

supports-condition

스타일 시트를 불러오기 위해 브라우저가 반드시 지원해야 하는 기능(들)을 나타내요. 브라우저가 supports-condition에 지정된 조건을 충족하지 않으면 연결된 스타일 시트를 가져오지 않을 수도 있고, 다른 경로를 통해 다운로드했더라도 로드하지 않습니다. supports()의 구문은 @supports에서 설명하는 것과 거의 똑같으니, 해당 주제를 참고하면 더 완벽하게 이해할 수 있을 거예요.

외부 스타일 시트(프레임워크, 위젯 스타일 시트, 라이브러리 등)를 특정 레이어로 가져오고 싶을 때는 layer 키워드나 layer() 함수와 함께 @import를 사용하면 된답니다.


설명 (Description)

불러온 규칙(Imported rules)은 @charset 규칙과 레이어를 생성하는 @layer 선언문을 제외한 다른 모든 유형의 규칙보다 먼저 나와야 해요.

잘못된 예시 (Invalid)

* {
  margin: 0;
  padding: 0;
}
/* 다른 스타일들 */
@import "my-imported-styles.css";

위처럼 @import 규칙을 일반 스타일 뒤에 선언하면 유효하지 않아서 브라우저가 그냥 무시해 버려요.

올바른 예시 (Valid)

@import "my-imported-styles.css";
* {
  margin: 0;
  padding: 0;
}
/* 다른 스타일들 */

또한, @import 규칙은 중첩된 문(nested statement)이 아니에요. 따라서 조건부 그룹 앳 규칙(conditional group at-rules) 내부에서는 사용할 수 없다는 점 주의하세요.

브라우저(사용자 에이전트)가 지원하지 않는 미디어 타입의 리소스를 굳이 가져오지 않도록, 개발자는 미디어 조건에 따른 임포트를 지정할 수 있어요. URL 뒤에 쉼표로 구분된 미디어 쿼리를 적어주면 되죠. 미디어 쿼리가 없으면 미디어 조건에 상관없이 항상 임포트해요. list-of-media-queriesall을 지정하는 것도 똑같은 효과를 냅니다.

마찬가지로, 브라우저는 특정 기능 세트의 지원 여부에 따라 리소스를 가져올 수 있도록 supports() 함수를 사용할 수 있어요. 이를 통해 개발자는 최신 CSS 기능을 활용하면서도 오래된 브라우저 버전에 대해서는 자연스러운 폴백(graceful fallbacks)을 제공할 수 있죠. 참고로 @import 규칙의 supports() 함수 내 조건들은 자바스크립트의 CSSImportRule.supportsText를 통해 가져올 수 있답니다.

@import 규칙은 연결된 리소스의 규칙들을 가져와서 캐스케이드 레이어를 만드는 데에도 사용할 수 있어요. 기존에 있던 레이어로 가져올 수도 있고요. 이때 layer 키워드나 layer() 함수를 씁니다. 이렇게 임포트된 스타일 시트의 선언들은 마치 임포트한 그 지점에 코드를 직접 쓴 것처럼 캐스케이드와 상호작용하게 돼요.


형식적인 구문 (Formal syntax)

@import = 
  @import [ <url> | <string> ] [ [ layer | layer( <layer-name> ) ] || [ scope | scope( <scope-start> | <scope-boundaries> ) ] || <supports-import-condition> ]? <media-import-condition> ;  

<layer-name> = 
  <ident> [ '.' <ident> ]* <scope-start> = 
  <selector-list>  

<scope-boundaries> = 
  [ ( <scope-start> ) ]? [ to ( <scope-end> ) ]?  

<supports-import-condition> = 
  supports( [ <supports-condition> | <declaration> ] )  

<media-import-condition> = 
  <media-query-list>  

<selector-list> = 
  <complex-selector-list>  

<scope-end> = 
  <selector-list>  

<supports-condition> = 
  not <supports-in-parens>                            |
  <supports-in-parens> [ and <supports-in-parens> ]* |
  <supports-in-parens> [ or <supports-in-parens> ]* <complex-selector-list> = 
  <complex-selector>#  

<supports-in-parens> = 
  ( <supports-condition> )  |
  <supports-feature>        |
  <general-enclosed>        

<complex-selector> = 
  <complex-selector-unit> [ <combinator>? <complex-selector-unit> ]* <supports-feature> = 
  <supports-selector-fn>        |
  <supports-font-tech-fn>       |
  <supports-font-format-fn>     |
  <supports-at-rule-fn>         |
  <supports-named-feature-fn>   |
  <supports-env-fn>             |
  <supports-decl>               

<general-enclosed> = 
  [ <function-token> <any-value>? ) ]  |
  [ ( <any-value>? ) ]                 

<complex-selector-unit> = 
  [ <compound-selector>? <pseudo-compound-selector>* ]!  

<combinator> = 
  '>'          |
  '+'          |
  '~'          |
  [ '|' '|' ]  

<supports-selector-fn> = 
  selector( <complex-selector> )  

<supports-font-tech-fn> = 
  font-tech( <font-tech> )  

<supports-font-format-fn> = 
  font-format( <font-format> )  

<supports-at-rule-fn> = 
  at-rule( <at-keyword-token> )  

<supports-named-feature-fn> = 
  named-feature( <ident> )  

<supports-decl> = 
  ( [ <declaration> | <supports-condition-name> ] )  

<compound-selector> = 
  [ <type-selector>? <subclass-selector>* ]!  

<pseudo-compound-selector> = 
  <pseudo-element-selector> <pseudo-class-selector>* <font-tech> = 
  <font-features-tech>  |
  <color-font-tech>      |
  variations            |
  palettes              |
  incremental           

<font-format> = 
  <string>            |
  collection          |
  embedded-opentype   |
  opentype            |
  svg                 |
  truetype            |
  woff                |
  woff2               

<type-selector> = 
  <wq-name>          |
  <ns-prefix>? '*'  

<subclass-selector> = 
  <id-selector>             |
  <class-selector>         |
  <attribute-selector>     |
  <pseudo-class-selector>  

<pseudo-element-selector> = 
  : <pseudo-class-selector>         |
  <legacy-pseudo-element-selector>  

<pseudo-class-selector> = 
  : <ident-token>                   |
  : <function-token> <any-value> )  

<font-features-tech> = 
  features-opentype  |
  features-aat       |
  features-graphite  

<color-font-tech> = 
  color-COLRv0  |
  color-COLRv1  |
  color-SVG      |
  color-sbix     |
  color-CBDT     

<wq-name> = 
  <ns-prefix>? <ident-token>  

<ns-prefix> = 
  [ <ident-token> | '*' ]? '|'  

<id-selector> = 
  <hash-token>  

<class-selector> = 
  '.' <ident-token>  

<attribute-selector> = 
  '[' <wq-name> ']'                                    |
  '[' <wq-name> <attr-matcher> [ <string-token> | <ident-token> ] <attr-modifier>? ']'  

<legacy-pseudo-element-selector> = 
  : [ before | after | first-line | first-letter ]  

<attr-matcher> = 
  [ '~' | '|' | '^' | '$' | '*' ]? '='  

<attr-modifier> = 
  i  |
  s  

이 구문은 CSS Cascading and Inheritance Level 5, Level 6, CSS Conditional Rules Module Level 3, Level 4, Level 5, CSS Fonts Module Level 5, Media Queries Level 5, Selectors Level 4 등 최신 표준들을 모두 반영하고 있어요. 모든 브라우저가 모든 기능을 다 구현한 것은 아닐 수 있으니 주의하세요!


예제 (Examples)

CSS 규칙 가져오기 (Importing CSS rules)

아래 두 예제는 URL을 <string> 형식으로 쓰는 법과 url() 함수로 쓰는 법을 보여줍니다.

@import "custom.css";
@import url("chrome://communicator/skin/communicator.css");

미디어 쿼리 조건에 따른 CSS 규칙 가져오기 (Importing CSS rules conditional on media queries)

이 예제들의 @import 규칙들은 연결된 CSS 규칙이 적용되기 위해 충족되어야 하는 미디어 관련 조건들을 보여줘요. 예를 들어 마지막 줄은 화면 장치(screen)이면서 가로 모드(landscape)일 때만 landscape.css를 불러오게 됩니다.

@import "fine-print.css" print;
@import "bluish.css" print, screen;
@import "common.css" screen;
@import "landscape.css" screen and (orientation: landscape);

기능 지원 여부에 따른 CSS 규칙 가져오기 (Importing CSS rules conditional on feature support)

아래 예제들은 display: grid를 지원하면 그리드 레이아웃 CSS를 가져오고, 지원하지 않으면 display: flex를 사용하는 CSS를 가져오는 방식을 보여줍니다.

@import "grid.css" supports(display: grid) screen and (width <= 400px);
@import "flex.css" supports((not (display: grid)) and (display: flex)) screen
  and (width <= 400px);

supports() 문은 하나만 쓸 수 있지만, 그 안에서 not, and, or를 사용해 여러 기능 체크를 조합할 수 있어요. 다만 이들을 섞어 쓸 때는 우선순위를 정하기 위해 반드시 괄호를 사용해야 합니다. (예: supports((..) or ((..) and (not (..))))는 유효하지만, 괄호가 부족하면 유효하지 않아요.) 만약 선언이 하나뿐이라면 첫 번째 예제처럼 추가 괄호로 감쌀 필요는 없답니다.

또한 supports() 안에 기본적인 선언문뿐만 아니라 CSS 함수를 지정할 수도 있어요. 해당 함수가 지원되고 브라우저에서 평가 가능하다면 true로 처리됩니다. 아래 코드는 자식 결합자(selector())와 font-tech() 함수 지원 여부에 따라 임포트하는 예시예요.

@import "whatever.css"
  supports((selector(h2 > p)) and (font-tech(color-COLRv1)));

캐스케이드 레이어로 CSS 규칙 가져오기 (Importing CSS rules into a cascade layer)

@import "theme.css" layer(utilities);

위 예제에서는 utilities라는 이름의 캐스케이드 레이어가 생성되고, 여기에 임포트된 theme 스타일 시트의 규칙들이 포함됩니다.

@import "headings.css" layer(default);
@import "links.css" layer(default);

@layer default {
  audio[controls] {
    display: block;
  }
}

이 경우 headings.csslinks.css에 들어있는 규칙들은 audio[controls] 규칙과 함께 동일한 default 레이어 안에서 캐스케이드 됩니다.

@import "theme.css" layer();
@import "style.css" layer;

이건 이름이 없는 두 개의 별도 캐스케이드 레이어를 만들고, 각각에 규칙을 가져오는 예시예요. 이름 없는 레이어는 생성될 때 확정(finalized)됩니다. 나중에 스타일을 재배치하거나 추가할 수 없고, 외부에서 참조할 수도 없죠.


@import는 파일을 나누어 관리할 때 정말 편리하지만, 너무 많이 사용하면 HTTP 요청이 많아져서 페이지 로딩 속도에 영향을 줄 수 있다는 점도 기억해야합니다.

profile
프론트에_가까운_풀스택_개발자

0개의 댓글