π What Is @import in CSS?
The @import rule allows you to load external CSS files into another stylesheet. It is often used to organize CSS into smaller, more manageable files. However β it comes with performance drawbacks. β οΈ
π§ Basic Syntax
Basic @import Syntax
@import url("styles.css");This imports styles.css into the current stylesheet so its styles apply automatically.
π Where Can You Use @import?
The @import rule must appear at the very top of your CSS file, before any other style rules.
Correct Usage
@import url("reset.css");
@import url("buttons.css");
body {
font-family: sans-serif;
}Incorrect Usage β
body {
background: #fff;
}
@import url("reset.css"); /* β Not allowed here */Note
π¨ Example: Organizing CSS with @import
main.css
@import url("layout.css");
@import url("colors.css");
@import url("typography.css");
.container {
padding: 20px;
}This separates your stylesheet into clean modules. But remember β every @import creates additional network requests.
β οΈ Performance Warning
@import is slower than using a standard <link> tag.
- β³ Each import may block rendering
- π‘ Browsers download imported CSS sequentially
- π Can hurt performance on large or mobile sites
Better Alternative: Use <link>
Recommended Method
<link rel="stylesheet" href="styles.css" />The <link> tag loads files faster and allows parallel downloads.
Note
π‘ Using @import with Media Queries
Import with Media Query
@import url("print.css") print;This loads the imported CSS only when the media type matches (e.g., printing).
π Multiple Ways to Use @import
Different @import Formats
@import "theme.css";
@import url("theme.css");
@import url(theme.css) screen and (min-width: 768px);π§© How @import Affects the Cascade
Imported files are treated as if their CSS is written at the very top of the stylesheet. Meaning:
- Rules inside imported files load before local CSS
- Local rules override imported rules unless specificity is higher
Cascade Example
/* imported.css */
p { color: blue; }
/* main.css */
@import url("imported.css");
p { color: red; }π Final color: red (source order wins).
π Best Practices
- Prefer <link> for loading CSS π
- Keep imports minimal
- Use imports mainly in SCSS/PostCSS, not vanilla CSS
- Avoid nested @import (very slow!)