Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Sử dụng @import Rule trong CSS

@import cho phép nhập (import) một file CSS khác vào stylesheet hiện tại. Tương tự <link> nhưng viết **bên trong CSS**.

Cú pháp

@import url("style.css");

Hoặc không dùng url():

@import "style.css";

Ví dụ trong HTML (trong <style>)

<head>
  <style>
    @import "base.css";
    @import "layout.css";
    @import "theme.css";
    /* custom rules */
  </style>
</head>

Ví dụ trong file CSS khác

/* main.css */
@import "reset.css";
@import "variables.css";
@import "components/button.css";
@import "components/card.css";

/* custom rules */

@import với Media Query (Conditional Import)

@import "print.css" print;
@import "mobile.css" screen and (max-width: 600px);

⚠️ Nhược điểm nghiêm trọng: Blocking Render

  • Browser phải **tải xong file @import** mới parse CSS tiếp → **chặn render (render-blocking)**.
  • <link> tải song song (parallel), @import tải tuần tự (serial) nếu lồng nhau.
  • Làm chậm **First Contentful Paint (FCP)** và **Largest Contentful Paint (LCP)**.

Khuyến nghị

  • KHÔNG dùng @import trong production (trừ build tool bundle).
  • Dùng <link rel="stylesheet"> cho tất cả file CSS.
  • Build tool (Webpack, Vite, Parcel, esbuild) sẽ **bundle** các @import/import thành 1 file CSS output → loại bỏ vấn đề blocking.
  • Nếu phải dùng: Đặt @import **ở đầu file CSS** (trước mọi rule khác), không lồng sâu.

Lịch sử

@import từ CSS1. CSS2 thêm media query cho @import. Hiện nay vẫn hợp lệ nhưng không khuyến khích cho performance.