CSS @import Rule

What Is @import?

The @import rule in CSS allows you to include one stylesheet inside another. This helps you organize styles into smaller, modular files and then combine them when needed.

Basic Syntax

Code Block Loading...

  • url() can reference absolute URLs (e.g., https://example.com/styles.css) or relative paths (e.g., ./styles.css).
  • Always wrap the file path in quotes for consistency.

Placement Matters

Important: @import directives must appear before any other CSS rules in the file. If you place them after selectors or properties, they will be ignored.

Using Media Queries with @import

You can conditionally load stylesheets for specific devices or contexts using media descriptors:

Code Block Loading...

This is useful for separating styles for different outputs (e.g., screen vs. print).

Advantages of @import

  • Keeps styles modular and organized
  • Allows conditional loading with media queries
  • Useful for quick prototyping or small projects

Limitations of @import

  • Performance impact: Each @import creates an additional HTTP request, which can slow down page loading.
  • Less control: Modern projects often prefer <link> tags in HTML for better performance and flexibility.
  • Browser quirks: Some older browsers may handle @import inconsistently.

Best Practices

  • Use <link> in HTML for production projects (faster and more reliable).
  • Reserve @import for small projects, modular experiments, or when working inside a single CSS file.
  • If you must use @import, keep them at the top of your stylesheet.
  • Consider modern alternatives like CSS preprocessors (Sass, Less) or build tools (Webpack, Vite) for managing multiple stylesheets.

Summary

Feature

@importRule

Tag in HTML

Placement

Inside CSS file

Inside of HTML

Performance

Slower (extra HTTP requests)

Faster, parallel loading

Media Queries

Supported

Supported

Best Use Case

Small projects, modular styles

Production websites

By understanding @import, you’ll know when it’s helpful and when to avoid it. For modern, scalable projects, prefer <link> tags or build tools but @import remains a handy tool for quick modular CSS management.