为啥表格标题和数据在 HTML 中放在同一行?
Posted
技术标签:
【中文标题】为啥表格标题和数据在 HTML 中放在同一行?【英文标题】:Why are table header and data placed in the same row in HTML?为什么表格标题和数据在 HTML 中放在同一行? 【发布时间】:2020-07-12 11:26:25 【问题描述】:我正在学习 html 表格。我有这个例子:
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;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Animals table</title>
<link href="styles/style.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>Animals table</h1>
<table>
<tr>
<th colspan="2">Animals</th>
</tr>
<tr>
<th colspan="2">Hippopotamus</th>
</tr>
<tr>
<th rowspan="2">Horse</th>
<td>Mare</td>
</tr>
<tr>
<td>Stallion</td>
</tr>
<tr>
<th colspan="2">Crocodile</th>
</tr>
<tr>
<th rowspan="2">Chicken</th>
<td>Hen</td>
</tr>
<tr>
<td>Rooster</td>
</tr>
</table>
</body>
</html>
我不明白为什么表头(Horse)和数据(Mare)放在同一行,然后另一个数据(Stallion)放在另一行,例如
<tr>
<th rowspan="2">Horse</th>
<td>Mare</td>
</tr>
<tr>
<td>Stallion</td>
</tr>
当我将第一个数据标签 (Mare) 移动到第二行时,我得到三列行。
那么,构造这样的表格背后的直觉是什么?不能用别的方法吗?
【问题讨论】:
【参考方案1】:您希望输出看起来如何?
您可能想了解行跨度和列跨度如何在 html 中工作。 This website 很好地解释了如何创建表格布局,就像您的示例中的那样。<th rowspan="2">Horse</th>
- > 这意味着马向下占据 2 个方块。因此,您输入的下一个 2 个表数据(td 或 th)将位于其右侧。在这种情况下,在 Horse 之后,您已经编写了 Mare 和 Stallion。
例如,如果您的行跨度为 3,它将以这种方式出现 V
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;
<table>
<tr>
<th rowspan="3">Horse</th>
<td>Mare</td>
</tr>
<tr>
<td>Stallion</td>
</tr>
<tr>
<td>Colt</td>
</tr>
</table>
另一方面,Colspan 沿行占用块。对于您表上的示例,您的表最多可以有 2 个 colspan,因为您的表只有 2 列。就像行中一样<tr><th colspan="2">Crocodile</th></tr>
该行不会添加任何其他内容。
我真的希望这已经回答了您的问题并使其更加清楚。
【讨论】:
以上是关于为啥表格标题和数据在 HTML 中放在同一行?的主要内容,如果未能解决你的问题,请参考以下文章
HTML 表单 - 添加新表格行并将焦点设置在第一个输入上的脚本