html - 我如何在 css 中水平居中 div 元素?

标签 html center css

我如何才能水平居中 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>

reference for the quirk behavior

关于html - 我如何在 css 中水平居中 div 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27867384/

相关文章:

html - 如何使多列滚动条菜单看起来像 Excel 电子表格

html - 将文本置于 float 元素之间

css - 为什么没有内部 div margin-right 和外部 div padding-right?

php - 标签打印机的 CSS

html - 导航栏间距

html - 将节内的文本居中

html - 目前,我们使用 CSS 使用图像作为复选框,当我单击复选框时,我想隐藏图像并显示背景颜色

javascript - IE8 和新的大众单位。好的 polyfill?

javascript - jQuery:用最短的时间完成处理程序

php - 将数组值发送到 mysql 数据库表