当设置table-layout:fixed
时,所有单元格都会变得相同大小,直到向其中添加一些内容为止。即使内容存在,有没有办法保持它们的大小相等?内容可以具有作为单元格百分比的宽度/高度,也可以具有固定宽度。该表格是响应式的(如果内容溢出,则应将其隐藏)。
现在的样子( jsfiddle ):
table {
table-layout: fixed;
width: 40vw;
height: 40vw;
}
td {
border: 3px solid grey;
padding: 0px;
width: 40px;
}
.aligner {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
overflow: hidden;
}
.content {
height: 60px;
width: 90%;
background-color: green;
border-radius: 20px;
}
<table>
<tr>
<td></td>
<td>
<div class="aligner">
</div>
</td>
<td></td>
</tr>
<tr>
<td></td>
<td>
<div class="aligner">
</div>
</td>
<td></td>
</tr>
<tr>
<td></td>
<td>
<div class="aligner">
<div class="content">
hello world
</div>
</div>
</td>
<td></td>
</tr>
</table>
如果可以仅使用 Flexbox(即没有表格)来解决它就好了,但我不知道如何使其始终具有固定数量的相同大小的行和列,以便它看起来像中的表格图像。
小:
中:
大:
最佳答案
仅使用CSS,您可以直接在td
上设置宽度
和高度
,并使用position:relative
+ overflow:hidden
,然后将内部 div 设置为 position:absolute
。
<强> jsFiddle
td {
border: 3px solid grey;
width: 10vw;
height: 10vw;
text-align: center;
position: relative;
overflow: hidden;
}
.aligner {
position: absolute;
left: 0; right: 0; top: 0; bottom: 0;
margin: auto;
height: 60px;
width: 90%;
background-color: green;
border-radius: 20px;
}
<table>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td><div class="aligner">hello world</div></td>
<td></td>
</tr>
</table>
或者使用伪元素+填充技巧来制作方形表格单元格。
<强> jsFiddle
table {
width: 40vw;
}
td {
border: 3px solid grey;
text-align: center;
position: relative;
overflow: hidden;
}
td:before {
content: "";
display: block;
padding-top: 100%;
}
.aligner {
position: absolute;
left: 0; right: 0; top: 0; bottom: 0;
margin: auto;
height: 60px;
width: 90%;
background-color: green;
border-radius: 20px;
}
<table>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td><div class="aligner">hello world</div></td>
<td></td>
</tr>
</table>
关于html - 如何确保单元格不会因内容而调整大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35256258/