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

Embedded/Internal Style Sheets (CSS nhúng/nội bộ) trong CSS

File CSS có thể được nhúng nội bộ (embedded/internal) bằng cách khai báo chúng trong thẻ <style>. Điều này giảm thời gian tải trang web (không cần HTTP request riêng). Tuy nhiên, CSS nhúng cho phép các style động, nhưng nó phải được tải lại tại mỗi request trang vì CSS nội bộ không thể được cache bởi trình duyệt. Internal CSS được khai báo trong thẻ <style> bên trong thẻ <head>.

Cú pháp

<style>
  /*declarations*/
</style>

Ví dụ 1: Internal CSS cơ bản

<!DOCTYPE html>
<html>
<head>
<style>
  article { font-size: 1.3em; font-family: cursive; }
  div { float: left; margin-left: 20px; width: 30px; height: 30px; background-color: lightgreen; box-shadow: 8px 5px 0 2px lightcoral; }
</style>
</head>
<body>
  <article>Demo text</article>
  <div></div> <div></div>
</body>
</html>

Kết quả

Embedded/Internal Style Sheets (CSS nhúng/nội bộ) trong CSS

Ví dụ 2: Internal CSS với border-radius

<!DOCTYPE html>
<html>
<head>
<style>
  div { float: left; margin-left: 20px; width: 60px; height: 30px; border-top-right-radius: 50px; border-bottom-right-radius: 50px; background-color: lightgreen; box-shadow: inset 5px 0 lightcoral; }
  div + div { background-color: lightblue; border-top-left-radius: 50px; border-bottom-left-radius: 50px; }
</style>
</head>
<body>
  <div></div> <div></div>
</body>
</html>

Kết quả

Embedded/Internal Style Sheets (CSS nhúng/nội bộ) trong CSS

So sánh 3 cách thêm CSS:

Phương phápƯu điểmNhược điểmKhi nào dùng
External (<link>)Cache được, tách biệt, tái sử dụng, maintainableHTTP request thêmProduction, multi-page sites
Internal (<style>)Không request thêm, override dễ dàng, dynamicKhông cache, lặp lại code, tăng HTML sizeSingle page, email templates, critical CSS inline
Inline (style="")Độ ưu tiên cao nhất, nhanh cho 1 elementKhông tái sử dụng, khó maintain, mixing concernsDynamic styles từ JS, email, temporary override

Critical CSS Pattern: Inline critical CSS (above-the-fold) trong <style>, load non-critical CSS async với <link rel="preload" as="style" onload="this.rel='stylesheet'">.