如何将div元素居中?它们只是彼此相邻,但不是中心。
div元素都包含一个固定宽度的图像,在图片下面是一个可变文本。
{{1}}
谢谢。
祝你好运
答案 0 :(得分:2)
使用display: inline-block;
并将text-align:center
应用于其容器,而不是浮点数:
#wrapper {
margin: 0 auto;
width: 900px;
max-width: 100%;
box-sizing: border-box;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
}
div>div>div {
display: inline-block;
}
div>div {
text-align: center;
}

<div id="wrapper">
<div style="max-width:900px;margin: 0 auto;">
<div style="width:100%;">
<div><img src="img" width="250" height="150"><br>This text goes under the Picture.</div>
<div><img src="img" width="250" height="150"><br>This text goes under the Picture.</div>
<div><img src="img" width="250" height="150"><br>This text goes under the Picture.</div>
<div><img src="img" width="250" height="150"><br>This text goes under the Picture.</div>
<div><img src="img" width="250" height="150"><br>This text goes under the Picture.</div>
<div><img src="img" width="250" height="150"><br>This text goes under the Picture.</div>
<div><img src="img" width="250" height="150"><br>This text goes under the Picture.</div>
</div>
</div>
</div>
&#13;
PS:如果你不喜欢DIV之间的小空间,你可以将每个结束DIV(</div>
)移动到下一行,直接在下一个开口前<div>
。这有助于避免HTML代码中的换行符导致的空白区域。
答案 1 :(得分:1)
您可以移除浮动并在父级上使用display: flex; justify-content: center; flex-wrap: wrap;
...并且您不需要包裹单元格的2个内部div。
#wrapper {
margin: 0 auto;
width: 900px;
max-width: 100%;
box-sizing: border-box;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
display: flex;
justify-content: center;
flex-wrap: wrap;
}
<div id="wrapper">
<div><img src="img" width="250" height="150"><br>This text goes under the Picture.</div>
<div><img src="img" width="250" height="150"><br>This text goes under the Picture.</div>
<div><img src="img" width="250" height="150"><br>This text goes under the Picture.</div>
<div><img src="img" width="250" height="150"><br>This text goes under the Picture.</div>
<div><img src="img" width="250" height="150"><br>This text goes under the Picture.</div>
<div><img src="img" width="250" height="150"><br>This text goes under the Picture.</div>
<div><img src="img" width="250" height="150"><br>This text goes under the Picture.</div>
<div><img src="img" width="250" height="150"><br>This text goes under the Picture.</div>
<div><img src="img" width="250" height="150"><br>This text goes under the Picture.</div>
</div>
答案 2 :(得分:0)
由于你有一个固定宽度的div,你可以简单地将位置设置为绝对值,左边为50%,边距设置为-450px(宽度的一半)
这是一个example
position:absolute;
left:50%;
margin:0 -450px;