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

Các cách nhúng CSS vào tài liệu HTML

Có 3 cách chính nhúng style sheet vào HTML:

1. External Stylesheet (File CSS riêng) - Khuyên dùng

File .css riêng, nhúng qua <link> trong <head>.

<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 quan hệ là stylesheet.
typetext/cssMIME type. Bắt buộc (HTML5 có thể bỏ, nhưng khuyên viết).
hrefURLBắt buộc. Đường dẫn file CSS.
mediascreen, print, all...Thiết bị đích. Mặc định all.

File style.css:

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

Nhúng: <link rel="stylesheet" href="style.css" media="all">

2. Embedded / Internal Stylesheet (<style>)

Viết CSS trực tiếp trong <head>.

<!DOCTYPE html>
<html>
  <head>
    <style media="all">
      body { background-color: orange; }
      h1 { color: yellow; margin-left: 30px; }
    </style>
  </head>
  <body>
    <h1>This is a heading</h1>
    <p>This is a paragraph.</p>
  </body>
</html>

Thuộc tính <style>: type="text/css" (mặc định), media (tùy chọn).

3. Inline Style (Attribute style)

Gán trực tiếp cho element.

<h2 style="color: #800000;">This is inline CSS</h2>

Ưu tiên (Cascade): Inline > Embedded > External (khi specificity bằng nhau).

4. @import Rule (trong CSS file hoặc <style>)

@import url("style.css");

Ít dùng do chặn render (blocking), khuyên dùng <link>.

Khuyến nghị

  • Production: **External stylesheet** (cache, maintainability, parallel download).
  • Development/Prototype: Embedded hoặc Inline cho nhanh.
  • Email HTML: Inline (nhiều client email strip <style>/<link>).