具有居中单元格的 HTML 表格



本质上我想要的是一个表格,有一行,5个单元格...... 第一个/左单元格应左对齐,最后一个/右对齐单元格应右对齐,中间 3 个单元格需要以每个单元格之间的间距相等量居中。表格本身是"100% 宽度",因此这就是单元格间距的来源。

我将如何编写这个(使用 html/css(?"表"标签或"div"等都是有效的,只要最终结果看起来正确,我真的不介意采用哪种方法。

编辑:问题是间距;表格本身不是问题,但简单地在单元格上设置对齐方式将无法正常工作;细胞之间的自由空间在细胞之间不是 100% 平均分配的。

我也不想指定单元格宽度,因为内容是动态的,无法事先知道需要多少宽度。

仅限 HTML 版本

<table>
<tr>
   <td width="20%"></td>
   <td width="20%" align="center"></td>
   <td width="20%" align="center"></td>
   <td width="20%" align="center"></td>
   <td width="20%" align="right"></td>
</tr>
</table>

CSS版本

<table>
<tr>
   <td style="width:20%;"></td>
   <td style="width:20%; text-align:center"></td>
   <td style="width:20%; text-align:center"></td>
   <td style="width:20%; text-align:center"></td>
   <td style="width:20%; text-align:right"></td>
</tr>
</table>

如果您使用的是表格,请为每个单元格分配唯一的 ID,然后根据需要使用 css 进行对齐,例如

.HTML:

<td id="firstcell">...</td>
<td id="secondcell">...</td>
<td id="thirdcell">...</td>
<td id="fourthcell">...</td>
<td id="fifthcell">...</td>

.CSS:

table {table-layout:fixed;}  /* ensure the widths are absolutely fixed at the specified width*/
td{ width: 20%;}  /* allocate space evenly between all 5 cells */
td#firstcell {text-align:left;}
td#secondcell, td#thirdcell, td#fourthcell {text-align:center;}
td#fifthcell {text-align:right;}
td
{
    text-align:center;
}
td:first-child
{
    text-align:left;   
}
td:last-child
{
    text-align:right;
}
<style type="text/css">
.five_columns {
    width: 100%;
}
.five_columns > div {
    width: 20%;
    float: left;
    text-align: center;
    overflow: auto;
}
.five_columns > div:first-child {
    text-align: left;
}
.five_columns > div:last-child {
    text-align: right;
}
</style>
<div class="five_columns">
    <div>...</div>
    <div>...</div>
    <div>...</div>
    <div>...</div>
    <div>...</div>
</div>

设置overflow: auto是因为如果您严格希望宽度相同,那么除了在任何太长的东西上强制滚动条之外,您真的无能为力(据我所知(。

最新更新