如何确保表格在任何屏幕尺寸上都是方形的.无论多少行/列



我正在尝试设置一个两行十六列的表格样式,使其在任何屏幕分辨率下始终为正方形。因此,单元格是纵向布局中的窄矩形。我尝试了以下方法:

.HTML:

<table>
<tr>
<td><div class="content"></div></td>
... *another 14 td's*   
<td><div class="content"></div></td>
</tr>
<tr>
<td><div class="content"></div></td>
... *another 14 td's*       
<td><div class="content"></div></td>
</tr>
</table>

.CSS:

table {
width:100%;
}
table:after {
content: '';
display: block;
margin-top: 100%;
}
td {
width: 6.25%;
position: relative;
}
td .content {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
background: yellow;
border: 1px solid brown;
}

我自己找到了解决方案,但仍然不明白。所以我的问题从"如何"变成了"为什么"。我也忘了提到,我在这个页面上使用了Bootstrap 4。所以整个解决方案在下面 - 它有效,我测试过。但是如果我在<div class = “square”>之前再添加<div>,它将不起作用。它仅在<div class = “col-*-*>(引导程序的类(在<div class = “square”>之前时才有效。

.HTML:

<div class = "row">
<div class = "col-sm-8">
<div class = "square">
<table>
<tr>
<td><div class="content"></div></td>
... *another 14 td's*
<td><div class="content"></div></td>
</tr>
<tr>
<td><div class="content"></div></td>
... *another 14 td's*
<td><div class="content"></div></td>
</tr>
</table>
</div>
</div>
</div>

.CSS:

.square {
width:100%;
height: 100%
}
.square:after {
content: '';
display: block;
margin-top: 100%;
}
table {
width:100%;
height: 100%;
}
td {
width: 6.25%;
position: relative;
}
td .content {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
background: yellow;
border: 1px solid brown;
}

不幸的是,目前还没有真正的好方法来设置相对于元素宽度的高度。您可以尝试的一种解决方案是将宽度和高度设置为静态数字,然后使用媒体查询,这样它就不会从页面中运行。像这样:

.table {
width: 100px;
height: 100px;
}
@media (min-width: 768px) {
.table {
height: 300px;
width: 300px;
}
}
@media (min-width: 1200px) {
.table {
width: 500px;
height: 500px;
}
}

回答第二个问题: Bootstrap使用flexbox,除非您另有指定,否则它将尝试将所有内容都放在同一行上。如果您将flex-wrap: wrap;设置为该引导类,那么它应该允许 100% 的内容填充该行并向上或向下增加其他内容。

最新更新