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

Cách nhúng CSS vào HTML: Inline, Internal, External

Để đưa CSS vào tài liệu HTML, chúng ta có ba cách: nhúng nội tuyến (inline), nhúng nội bộ (internal), hoặc liên kết file ngoài (external).

Cú pháp tóm tắt

<!-- Inline -->
<element style="/* declarations */"></element>

<!-- Internal -->
<head>
    <style> /* declarations */ </style>
</head>

<!-- External -->
<head>
    <link rel="stylesheet" href="#location">
</head>

1. Inline CSS (Nhúng nội tuyến)

Viết CSS trực tiếp trong thuộc tính style của phần tử.

<!DOCTYPE html>
<html>
<head></head>
<body>
<p style="font-family: Forte;">Demo text</p>
<p style="background-color: lightblue;">This is Demo text</p>
<img src="image.jpg" style="border: 3px groove orange;">
</body>
</html>

Ưu điểm: Nhanh, test ngay. Nhược điểm: Lặp code, khó bảo trì, độ ưu tiên cao ghi đè mọi thứ.

2. Internal CSS (Nhúng nội bộ)

Viết CSS trong thẻ <style> bên trong <head>.

<!DOCTYPE html>
<html>
<head>
<style>
div {
    margin: auto;
    padding: 15px;
    width: 33%;
    border: 2px solid;
    border-radius: 5%;
}
div > div { border-color: transparent; box-shadow: inset 0 0 6px red; }
div > div > div { border-color: red; }
</style>
</head>
<body>
<div><div></div><div><div></div></div><div></div></div>
</body>
</html>

Ưu điểm: Tách HTML/CSS trong cùng file, phù hợp trang đơn, email HTML. Nhược điểm: Không tái sử dụng được cho trang khác.

3. External CSS (Liên kết file ngoài) — Khuyến nghị

Tách CSS vào file .css riêng, liên kết bằng <link>.

<!-- HTML file -->
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <p>Demo text</p>
    <p>Demo text again</p>
</body>
</html>

<!-- style.css -->
p {
    text-decoration: overline;
    text-transform: capitalize;
}

Ưu điểm: Tái sử dụng cho nhiều trang, cache trình duyệt, tách biệt trách nhiệm, dễ bảo trì, team làm việc song song.

Thứ tự ưu tiên (Cascade)

Inline > Internal/External (theo thứ tự khai báo) > Browser default.

Best Practice hiện đại

  • Luôn dùng External CSS cho dự án thực tế
  • Gom nhiều file CSS nhỏ thành một file khi deploy (build tool: Vite, Webpack)
  • Dùng <link rel="preload" as="style"> cho CSS critical
  • Tránh inline style trừ khi dynamic style từ JS