小编典典
我之前的答案显示了一种坦率地说已经过时的方法(它仍然有效,只有更好的方法可以实现此目的)。因此,我正在对其进行更新,以包括一个更现代的flexbox解决方案。
在这里查看支持;在大多数环境中,使用安全。
这利用了:
display: flex:以flexbox行为显示此元素
justify-content: center 将内部元素沿容器的主轴中心对齐
flex-wrap: wrap 确保内部元素自动包裹在容器中(不要脱离容器)
注意:与HTML和CSS一样,这只是获得所需结果的 多种 方法之一。在选择适合 您的 规格的方法之前,请彻底研究。
.container {
display: flex;
justify-content: center;
flex-wrap: wrap;
width: 70%;
background: #eee;
margin: 10px auto;
position: relative;
text-align:center;
}
.block {
background: green;
height: 100px;
width: 100px;
margin: 10px;
}
原始答案
您可以将样式text-align:center;应用于容器,并将.blocks 显示为内联块元素:
.container {
width: 70%;
background: #eee;
margin: 10px auto;
position: relative;
text-align:center;
}
.block {
background: green;
height: 100px;
width: 100px;
display:inline-block;
margin: 10px;
}
请注意,我已注释掉
2020-05-16