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

Cách đưa CSS vào trang HTML (Bản mở rộng)

Chúng ta có thể đưa CSS vào trang HTML theo ba cách: Inline, Internal, External.

So sánh chi tiết

CáchCú phápPhạm viTái sử dụngĐộ ưu tiên
Inlinestyle="..."1 phần tửKhôngCao nhất
Internal<style> trong <head>1 trangKhôngTrung bình
External<link rel="stylesheet">Nhiều trangCóThấp nhất

Ví dụ Inline CSS

<!DOCTYPE html>
<html>
<head></head>
<body>
<div style="background-color:mistyrose; height: 50px;"></div>
<p style="letter-spacing: 16px; font-size: 1.3em;">
    <u>Demo text here</u>
</p>
</body>
</html>

Ví dụ Internal CSS

<!DOCTYPE html>
<html>
<head>
<style>
table, table * {
    border: 5px double green;
    margin: auto;
    padding: 20px;
}
tr { box-shadow: 0 0 0 3px red; }
td { border-color: blue; }
</style>
</head>
<body>
<table>
    <tr><td></td><td></td></tr>
    <tr><td></td><td></td></tr>
</table>
</body>
</html>

Ví dụ External CSS

<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <div>
        <div></div>
        <div><div></div></div>
        <div></div>
    </div>
</body>
</html>

<!-- style.css -->
div {
    margin: auto;
    padding: 15px;
    width: 33%;
    border: 2px solid;
    border-radius: 50%;
}
div > div { border-color: green; }
div > div > div { border-color: red; }

Mẹo nâng cao

  • Multiple stylesheets: <link rel="stylesheet" href="reset.css"> <link rel="stylesheet" href="main.css">
  • Media-specific: <link rel="stylesheet" href="print.css" media="print">
  • Preload: <link rel="preload" href="critical.css" as="style" onload="this.rel='stylesheet'">
  • CSS Modules / Scoped CSS: Dùng với React, Vue, Svelte để tránh xung đột class