您只能使用 CSS 制作具有垂直和水平居中内容的响应式正方形网格。我将逐步解释如何进行,但首先这里有 2 个演示,说明您可以实现的目标:
现在让我们看看如何制作这些花哨的响应方块!
1.制作响应方块:
保持元素正方形(或任何其他纵横比)的技巧是使用百分比padding-bottom。
旁注:您也可以使用顶部填充或顶部/底部边距,但元素的背景不会显示。
由于顶部填充是根据父元素 (See MDN for reference) 的宽度计算的,因此元素的高度将根据其宽度而变化。您现在可以根据其宽度保持其纵横比。
此时可以编码:
HTML:
<div></div>
CSS:
div {
width: 30%;
padding-bottom: 30%; /* = width for a square aspect ratio */
}
这是一个 simple layout example 的 3*3 方格网格,使用上面的代码。
使用这种技术,您可以制作任何其他纵横比,这里有一个表格,给出了根据纵横比和 30% 宽度的底部填充值。
Aspect ratio | padding-bottom | for 30% width
------------------------------------------------
1:1 | = width | 30%
1:2 | width x 2 | 60%
2:1 | width x 0.5 | 15%
4:3 | width x 0.75 | 22.5%
16:9 | width x 0.5625 | 16.875%
2。在方块内添加内容:
由于您不能直接在正方形内添加内容(它会扩大它们的高度并且正方形不再是正方形),因此您需要在其中创建子元素(在此示例中我使用 div)position: absolute;并将内容放入其中。这会将内容从流中取出并保持正方形的大小。
不要忘记在父 div 上添加 position:relative;,以便绝对子级相对于其父级进行定位/大小。
让我们在 3x3 方格中添加一些内容:
HTML:
<div class="square">
<div class="content">
.. CONTENT HERE ..
</div>
</div>
... and so on 9 times for 9 squares ...
CSS:
.square {
float: left;
position: relative;
width: 30%;
padding-bottom: 30%; /* = width for a 1:1 aspect ratio */
margin: 1.66%;
overflow: hidden;
}
.content {
position: absolute;
height: 80%; /* = 100% - 2*10% padding */
width: 90%; /* = 100% - 2*5% padding */
padding: 10% 5%;
}
RESULT
3。内容居中:
水平:
这很简单,您只需将text-align:center 添加到.content。
RESULT
垂直对齐:
这变得严重了!诀窍是使用
display: table;
/* and */
display: table-cell;
vertical-align: middle;
但是我们不能在.square 或.content div 上使用display:table;,因为它与position:absolute; 冲突,所以我们需要在.content div 中创建两个子级。我们的代码将更新如下:
HTML:
<div class="square">
<div class="content">
<div class="table">
<div class="table-cell">
... CONTENT HERE ...
</div>
</div>
</div>
</div>
... and so on 9 times for 9 squares ...
CSS:
.square {
float:left;
position: relative;
width: 30%;
padding-bottom : 30%; /* = width for a 1:1 aspect ratio */
margin:1.66%;
overflow:hidden;
}
.content {
position:absolute;
height:80%; /* = 100% - 2*10% padding */
width:90%; /* = 100% - 2*5% padding */
padding: 10% 5%;
}
.table{
display:table;
height:100%;
width:100%;
}
.table-cell{
display:table-cell;
vertical-align:middle;
height:100%;
width:100%;
}
我们现在已经完成了,我们可以在这里看看结果:
editable fiddle here