首页 > 解决方案 > 将列标题与 CSS/HTML 中的数据对齐

问题描述

我正在学习如何在 HTML 中制作表格,但是“c”列标题与其数据不对齐,而是与“b”列标题组合在一起。

输出:

表格标题不正确的表格

这是代码:

table,th,td{
  padding:20px;
  border:10px solid navy;
}
    <body>
        <table>
            <th>a</th>
            <th>b</th>
            <th>c</th>
            <tr>
                <td>1</td>
                <td colspan="30">Apples</td>
                <td><form>
                    <input type="checkbox" name="50g"/>0.5Kg
                    <input type="checkbox" name="50g"/>1Kg
                    <input type="checkbox" name="bag"/>Paper Bag?
                </td></form>
            </tr>
            <tr>
                <td>1</td>
                <td colspan="30">Apples</td>
                <td><form>
                    <input type="checkbox" name="50g"/>0.5Kg
                    <input type="checkbox" name="50g"/>1Kg
                    <input type="checkbox" name="bag"/>Paper Bag?
                </td></form>
            </tr>
            <tr>
                <td>1</td>
                <td colspan="30">Apples</td>
                <td><form>
                    <input type="checkbox" name="50g"/>0.5Kg
                    <input type="checkbox" name="50g"/>1Kg
                    <input type="checkbox" name="bag"/>Paper Bag?
                </td></form>
            </tr>

        </table>
    </body>

我尝试更改<th>"c" 和 "b" 标记中的填充值,但似乎无法解决问题。我该如何解决?

标签: htmlcss

解决方案


两件事可以解决您的问题。

  1. 确保您的 HTML 有效。您的 HTML 当前无效,因为您在收盘</td>前有收盘</form>。应该是这样的</form></td>
  2. 从 every 中删除colspan="30"属性td,将其更改为:
<td colspan="30">Apples</td>

<td>Apples</td>

colspan指示单元格扩展了多少列。现在它扩展到 30 列,而您没有那么多列。在 MDN 上阅读更多内容

<html>
<style>
  table,
  th,
  td {
    padding: 20px;
    border: 10px solid navy;
  }
</style>

<body>
  <table>
    <th>a</th>
    <th>b</th>
    <th>c</th>
    <tr>
      <td>1</td>
      <td>Apples</td>
      <td>
        <form>
          <input type="checkbox" name="50g" />0.5Kg
          <input type="checkbox" name="50g" />1Kg
          <input type="checkbox" name="bag" />Paper Bag?
        </form>
      </td>

    </tr>
    <tr>
      <td>1</td>
      <td>Apples</td>
      <td>
        <form>
          <input type="checkbox" name="50g" />0.5Kg
          <input type="checkbox" name="50g" />1Kg
          <input type="checkbox" name="bag" />Paper Bag?
        </form>
      </td>
    </tr>
    <tr>
      <td>1</td>
      <td>Apples</td>
      <td>
        <form>
          <input type="checkbox" name="50g" />0.5Kg
          <input type="checkbox" name="50g" />1Kg
          <input type="checkbox" name="bag" />Paper Bag?
        </form>
      </td>
    </tr>

  </table>
</body>

</html>


推荐阅读