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

Nhúng file CSS ngoài (External Stylesheet) vào HTML

External Stylesheet: File .css riêng biệt, nhúng vào HTML qua thẻ <link> trong <head>. Cách **khuyên dùng nhất** cho production.

Cú pháp

<head>
  <link rel="stylesheet" type="text/css" href="style.css" media="all" />
</head>

Thuộc tính <link>

AttributeValueMô tả
relstylesheetBắt buộc. Xác định relationship là stylesheet.
typetext/cssMIME type. HTML5 có thể bỏ, nhưng khuyên viết.
hrefURLBắt buộc. Đường dẫn file CSS (relative hoặc absolute).
mediascreen, print, all, (max-width: 600px)...Media query. Mặc định all.
titlestringTên stylesheet (dùng cho alternate stylesheet).

Ví dụ file CSS (style.css)

h1, h2, h3 {
  color: #36C;
  font-weight: normal;
  letter-spacing: .4em;
  margin-bottom: 1em;
  text-transform: lowercase;
}

Nhúng trong HTML

<head>
  <link rel="stylesheet" type="text/css" href="style.css" media="all" />
</head>

Lợi ích External Stylesheet

  • Cache: Browser cache file CSS riêng → load nhanh lần sau.
  • Tách biệt: HTML structure, CSS presentation → dễ bảo trì, teamwork.
  • Reuse: 1 file CSS cho nhiều trang HTML.
  • Parallel download: Browser tải CSS song song với HTML (nếu đặt <link> sớm trong <head>).
  • Preload/Preconnect: <link rel="preload" as="style" href="style.css"> tải sớm hơn.

Best practice

  • Đặt <link> ở **đầu <head>** (sau charset, title) để không chặn render.
  • Gom CSS chung thành 1 file (hoặc ít file) → giảm HTTP request (HTTP/1.1). HTTP/2 ít quan trọng hơn.
  • Minify + Gzip/Brotli compression.
  • Dùng media="print" cho print stylesheet (load không block render).