1. 程式人生 > 實用技巧 >HTML基礎10--表格的使用

HTML基礎10--表格的使用

HTML表格

在HTML中構建表格資料可以讓web顯示資料變得更容易,表格在實際的生活中是極其常見的直觀的表達方式

建立一個表格
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link href="table.css" rel="stylesheet" type="text/css">
    <title>TABLE</title>
</head>
<body>
<table>
    <tr>
      <td>表格1</td>
      <td>表格2</td>
      <td>表格3</td>
      <td>表格4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
</table>
</body>
</html>

設定CSS表格樣式

html {
  font-family: sans-serif;
}

table {
  border-collapse: collapse;
  border: 2px solid rgb(200,200,200);
  letter-spacing: 1px;
  font-size: 0.8rem;
}

td, th {
  border: 1px solid rgb(190,190,190);
  padding: 10px 20px;
}

th {
  background-color: rgb(235,235,235);
}

td {
  text-align: center;
}

tr:nth-child(even) td {
  background-color: rgb(250,250,250);
}

tr:nth-child(odd) td {
  background-color: rgb(245,245,245);
}

caption {
  padding: 10px;
}

開啟瀏覽器

單元格跨越多行和列

需要用到colspan和rowspan兩個屬性

公眾號:伊洛的小屋
個人主頁:https://yiluotalk.com/
部落格園:https://www.cnblogs.com/yiluotalk/
<html>
  <head>
    <meta charset="utf-8">
    <title>表格TITLE</title>
    <link href="table.css" rel="stylesheet" type="text/css">
  </head>
  <body>
    <h1>城市表格</h1>
    <table>
      <tr>
        <th colspan="2">北京</th>
      </tr>
      <tr>
        <th colspan="2">上海</th>
      </tr>
      <tr>
        <th rowspan="2">廣東</th>
        <td>廣州</td>
      </tr>
      <tr>
        <td>深圳</td>
      </tr>
      <tr>
        <th colspan="2">天津</th>
      </tr>
      <tr>
        <th rowspan="2">遼寧</th>
        <td>瀋陽</td>
      </tr>
      <tr>
        <td>大連</td>
      </tr>
    </table>
  </body>
</html>

開啟瀏覽器

共同的樣式

HTML有一種方法可以定義整列資料的樣式資訊,

為表格增加標題

通過元素

<html>
  <head>
    <meta charset="utf-8">
    <title>表格TITLE</title>
    <link href="table.css" rel="stylesheet" type="text/css">
  </head>
  <body>
    <h1>城市表格</h1>
    <table>
        <caption>中國城市</caption>
      <tr>
        <th colspan="2">北京</th>
      </tr>
      <tr>
        <th colspan="2">上海</th>
      </tr>
      <tr>
        <th rowspan="2">廣東</th>
        <td>廣州</td>
      </tr>
      <tr>
        <td>深圳</td>
      </tr>
      <tr>
        <th colspan="2">天津</th>
      </tr>
      <tr>
        <th rowspan="2">遼寧</th>
        <td>瀋陽</td>
      </tr>
      <tr>
        <td>大連</td>
      </tr>
    </table>
  </body>
</html>

標題放在下面,開啟瀏覽器檢視效果