我如何才能水平居中 div 元素,以便当我更改浏览器的宽度时,最后一个 div 会随着 css 下降?
所以:
---||||-||||-||||---
--------||||--------
当我写的时候:
<div style="float: left; position: relative; left: 50%;">
<div style="float: left; position: relative; left: -50%;">
<div style="width:315px; height:340px; float: left; margin-top: 10px; margin-bottom: 10px;">Text</div>
<div style="width:315px; height:340px; float: left; margin-top: 10px; margin-bottom: 10px;">Text</div>
...
</div>
</div>
然后一个元素往下走之后,所有的div元素往左边走。
最佳答案
我建议在元素上使用 display: inline-block
然后在容器上使用 text-align: center
来处理你想要的居中:
我清理了您的 HTML,但这里是基本的 HTML 格式,包含一个 container
类和多个(任意数量)block
类 DIV:
<div class="container">
<div class="block">Text</div>
<div class="block">Text</div>
<div class="block">Text</div>
</div>
CSS 修改 block 的显示设置和容器的文本对齐方式:
div.block {
display: inline-block; /* this changes the elements to behave more like inline elements (think <span>s) */
width: 315px;
margin: 10px 0;
height: 340px;
}
div.container {
width: 100%;
text-align: center; /* this is the magic that centers the elements */
}
我整理了一个应该有助于演示此方法的小演示: JSFIDDLE
注意:display: inline-block
CSS 存在一个小“怪癖”。它会导致元素之间出现少量空间。这可以通过多种方式删除,我的首选方法是使用注释或包装 DIV 的结束标记。 (问题是由 HTML 中元素之间的回车/空格引起的):
<div class="container">
<div class="block">Text</div><!--
--><div class="block">Text</div><!--
--><div class="block">Text</div>
</div>
<div class="container">
<div class="block">Text</div
><div class="block">Text</div
><div class="block">Text</div>
</div>
关于html - 我如何在 css 中水平居中 div 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27867384/