这是我的代码:
.table1 {
background-color: gray;
display: flex;
justify-content: ;
align-items: ;
height: 400px;
margin-left: 40px;
padding-left: ;
}
.table1 tr {
background-color: blue;
height: 50px;
width: 50px;
}
<table class="table1">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
为什么我可以更改"TR"的高度,但我不能更改宽度?
是的,我知道我可以在父块上使用填充来更改宽度,但是为什么它不能像更改高度那样仅通过更改 TR 元素本身的宽度来工作?
尝试在tbody
上设置flex
flex-direction: column
,如下所示:
.table1 tbody {
background-color: gray;
display: flex;
justify-content: ;
align-items: ;
height: 400px;
margin-left: 40px;
padding-left: ;
flex-direction: column;
}
.table1 tr {
background-color: blue;
height: 50px;
}
.table1 tr td, .table1 tr th {
width: 150px;
text-align: left;
}
<table class="table1">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
请注意,我刚刚将width
添加到td
和th
中。
正如其他人提到的,tr
始终是表格本身宽度的 100%,但高度属性是可调的。这就是为什么代码中的 height 属性有效但宽度属性不起作用的原因。
要调整列的宽度属性,您所要做的就是定位th
元素。例如,如果将以下代码添加到CSS工作表中,则会看到宽度发生变化。
th {
width:50px;
}
或者,为了更具体,您可以执行以下操作。
.table1 tr th {
width:50px;
}
您还可以为每列设置不同的宽度。例如,"名字"列可以是 100 像素,而"姓氏"列可以是 150 像素。 不言而喻,但所有列的总组合宽度不应超过表本身的宽度。