我想让一组图像在页面上水平显示。每个图像下方都有一些链接,因此我需要在每个图像/链接组周围放置一个容器。
我最想要的就是将它们放在float:left的div中。问题是我希望容器对齐中心而不是左对齐。我该如何做到这一点。
Answers:
使用display:inline-block;
而不是浮动
您不能将浮动框居中,而将内嵌块居中放置,就好像它们是文本一样,因此在“行”的外部整体容器上-您可以text-align: center;
为每个图像/标题容器设置(可以是inline-block;
) -如果需要,请向左对齐文本
font-size:0
并将其还原到子元素上。或letter-spacing:-.31em
在父母和letter-spacing:0
孩子身上使用。
vertical-align:middle
同时使用display:inline-block
。
如今, CSS Flexbox得到了很好的支持。转到此处,获得有关flexbox的良好教程。
在所有较新的浏览器中都可以正常工作:
#container {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.block {
width: 150px;
height: 150px;
background-color: #cccccc;
margin: 10px;
}
<div id="container">
<div class="block">1</div>
<div class="block">2</div>
<div class="block">3</div>
<div class="block">4</div>
<div class="block">5</div>
</div>
有人可能会问为什么不使用display:inline-block?对于简单的事情,这很好,但是如果您在块中包含复杂的代码,则布局可能不再正确居中。Flexbox比向左浮动更稳定。
尝试这样:
<div id="divContainer">
<div class="divImageHolder">
IMG HERE
</div>
<div class="divImageHolder">
IMG HERE
</div>
<div class="divImageHolder">
IMG HERE
</div>
<br class="clear" />
</div>
<style type="text/css">
#divContainer { margin: 0 auto; width: 800px; }
.divImageHolder { float:left; }
.clear { clear:both; }
</style>
也许这就是您正在寻找的-https://www.w3schools.com/css/css3_flexbox.asp
CSS:
#container {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.block {
width: 150px;
height: 150px;
margin: 10px;
}
HTML:
<div id="container">
<div class="block">1</div>
<div class="block">2</div>
<div class="block">3</div>
</div>
.contentWrapper {
float: left;
clear: both;
margin-left: 10%;
margin-right: 10%;
}
.repeater {
height: 9em;
width: 9em;
float: left;
margin: 0.2em;
position: relative;
text-align: center;
cursor: pointer;
}