πŸ“₯ Understanding the @import Rule in CSS

πŸ“Œ 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. ⚠️

>>β€œOrganize smartly, but load wisely.”

πŸ”§ 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

All @import rules must come before any selectors.

🎨 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

Use @import only in controlled environments (small projects, preprocessors, or when working with older codebases).

πŸ’‘ 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!)

πŸ”— Useful Resources

>>β€œKeep your CSS modular β€” but keep it fast.” ⚑