我尝试在特定列上设置列宽,但它不起作用。我的 table 是 layout=fixed
和 width=100%
.我设置了max-width=300px
对于其中一列但没有任何变化,所有列均匀分布在表中。我的表格没有响应固定列宽。
CSS:
table {
table-layout: fixed;
border-collapse: collapse;
width: 100%;
}
HTML:
<div class="container-fluid">
<table class="table table-hover ml-3 mr-3">
<tr class="headers bg-primary text-white headers">
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Account)
</th>
<th>
@Html.DisplayNameFor(model => model.Day)
</th>
</tr>
<tbody id="myTable" class="align-middle">
<tr>
<td style="word-wrap: break-word; white-space:normal">
@Html.DisplayFor(modelItem => item.Name)
</td>
<td style="max-width: 300px"> <!-- here I set column width -->
@Html.DisplayFor(modelItem => item.Account)
</td>
<td>
@Html.DisplayFor(modelItem => item.Day)
</td>
</tr>
</tbody>
</table>
</div>
添加style="max-width: 300px"
至 <th>
也无济于事。
还有 ml-3
和 mr-3
效果不好,我只在左边添加了 margin 。此外,水平滚动条出现在表格的底部。
这是它的样子:
最佳答案
max-width
属性只适用于 block 元素,所以需要应用display:block
:
<td style="max-width: 300px; display: block; margin: auto;">
XYZ
</td>
table {
table-layout: fixed;
border-collapse: collapse;
width: 100%;
}
tbody > tr > td {
vertical-align: middle;
text-align: center;
}
<div class="container-fluid">
<table class="table table-hover ml-3 mr-3">
<tr class="headers bg-primary text-white headers">
<th>
Name
</th>
<th>
Account
</th>
<th>
Day
</th>
</tr>
<tbody id="myTable" class="align-middle">
<tr>
<td style="word-wrap: break-word; white-space:normal">
XYZ
</td>
<td style="max-width: 300px; display: block; margin: auto;"> <!-- here I set column width -->
XYZ
</td>
<td>
XYZ
</td>
</tr>
</tbody>
</table>
</div>
关于html - layout=fixed 时无法更改列宽和边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65049386/