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

Cách hiển thị màu nền (background color) của phần tử trong HTML?

Thuộc tính bgcolor từng dùng trên <body>, <table>, <td>, <th>... để đặt màu nền. Đã deprecated trong HTML5, thay bằng CSS.

Ví dụ cũ (3 định dạng màu)

<!DOCTYPE html>
<html>
  <head>
    <title>Màu nền HTML</title>
  </head>
  <body>
    <!-- Tên màu -->
    <table bgcolor="yellow" width="100%">
      <tr><td>Nền vàng</td></tr>
    </table>
    <!-- Hex -->
    <table bgcolor="#6666FF" width="100%">
      <tr><td>Nền xanh dương nhạt</td></tr>
    </table>
    <!-- RGB -->
    <table bgcolor="rgb(255,0,255)" width="100%">
      <tr><td>Nền magenta</td></tr>
    </table>
  </body>
</html>

Cách hiện đại với CSS

<!DOCTYPE html>
<html>
  <head>
    <style>
      .yellow-bg { background-color: yellow; }
      .hex-bg { background-color: #6666FF; }
      .rgb-bg { background-color: rgb(255, 0, 255); }
      .rgba-bg { background-color: rgba(0, 255, 0, 0.3); } /* có trong suốt */
    </style>
  </head>
  <body>
    <div class="yellow-bg">Nền vàng</div>
    <div class="hex-bg">Nền xanh dương nhạt</div>
    <div class="rgb-bg">Nền magenta</div>
    <div class="rgba-bg">Nền xanh lá trong suốt</div>
  </body>
</html>

CSS background nâng cao

  • background-image, background-gradient
  • background-size, background-position, background-repeat
  • background: linear-gradient(to right, red, blue);