我在容器内有两排盒子,我需要它们位于页面的中心。我无法设置容器的宽度,因为里面的东西可能会改变。
我之所以不在HTML内将框分成两行,是因为我在屏幕紧时使用媒体查询来强制两行,但是当屏幕上有空间时,我自然会将其强制为两行。
请注意,我的clearfix有一个空的div。如果您认为有更好的方法,请随时将其删除。
这是我的HTML:
<div class="container">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
<div style="clear: both;"></div>
</div>
这是我的CSS:
.box {
width: 50px;
height: 50px;
background: red;
color: white;
margin: 10px;
float: left;
}
.box:nth-child(3) {
clear: both;
}
.container {
background-color: grey;
}
容器是灰色的,仅供说明,在我的应用程序中会很清楚。
在这里摆弄
如果可以包装元素,则可以将display
wrapper元素的设置为inline-block
,然后添加text-align: center
到父元素以进行水平居中:
.container {
background-color: grey;
text-align: center;
}
.container .center-wrapper {
display: inline-block;
}
.box {
text-align: left;
}
.box {
width: 50px;
height: 50px;
background: red;
color: white;
margin: 10px;
float: left;
text-align: left;
}
.box:nth-child(3) {
clear: both;
}
.container {
background-color: grey;
text-align: center;
}
.container .center-wrapper {
display: inline-block;
}
<div class="container">
<div class="center-wrapper">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
<div style="clear: both;"></div>
</div>
</div>
使用弹性框,您还可以使用以下内容:
.container {
background-color: grey;
display: flex;
justify-content: center;
}
.box {
width: 50px;
height: 50px;
background: red;
color: white;
margin: 10px;
float: left;
}
.box:nth-child(3) {
clear: both;
}
.container {
background-color: grey;
display: flex;
justify-content: center;
}
<div class="container">
<div class="center-wrapper">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
<div style="clear: both;"></div>
</div>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句