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

Tạo định nghĩa kiểu (style definition) trong HTML với thẻ <style>


Thẻ <style> nhúng CSS trực tiếp vào HTML, đặt trong <head> (khuyên dùng) hoặc <body>.

Thuộc tính

Thuộc tínhGiá trịMô tả
typetext/cssLoại stylesheet (mặc định HTML5, có thể bỏ)
mediascreen, print, all, speech...Thiết bị đích (responsive print...)
titletextTiêu đề cho stylesheet (alternate stylesheet)
scopedboolean (deprecated)Chỉ áp dụng cho parent element (HTML5.1, đã bỏ)

Ví dụ cơ bản

<!DOCTYPE html>
<html>
<head>
  <style>
    table, th, td { border: 1px solid black; border-collapse: collapse; }
    th, td { padding: 8px 12px; }
    th { background: #333; color: white; }
  </style>
</head>
<body>
  <h3>Bảng Xếp Hạng</h3>
  <table>
    <tr><th>Hạng</th></tr>
    <tr><td>Nhất</td></tr>
    <tr><td>Nhì</td></tr>
    <tr><td>Ba</td></tr>
  </table>
</body>
</html>

Ví dụ media print

<style media="print">
  .no-print { display: none !important; }
  body { font-size: 12pt; color: black; }
  a::after { content: " (" attr(href) ")"; }
</style>

Best practices

  • Ưu tiên <link rel="stylesheet"> cho file CSS riêng (cache, maintainability)
  • Dùng <style> cho: critical CSS (above-the-fold), dynamic styles, email HTML
  • Tránh inline style style="..." trừ khi dynamic từ JS