html - 居中一个没有设置宽度的div容器

标签 html css

我正在尝试以响应方式将我的 div 居中。但是如果不设置宽度我无法做到这一点......

<div class="wrapper">
    <div class="container">
        <div class="left box">Content</div>
        <div class="right box">Content</div>
    </div>
</div>

.wrapper {text-align:center}
.container {width:100%; margin: 10px auto}
.left {width:69%;max-width:350px; background:blue}
.right {width:29%;max-width:150px; background:red}
.box {float:left;padding:20px}

如何将 .container 放在中间?

演示:http://jsfiddle.net/z9zydnwL/

最佳答案

Flexbox甚至可以让漂浮的 child 居中!

所以我可以简单地将 display:flexjustify-content: center; 添加到容器中

.container {
    margin: 10px auto;
    display:flex;
    justify-content: center; /* align horizontal */
}

FIDDLE

Browser support这几天也不错

.wrapper {
  width: 100%;
  text-align: center
}
.container {
  margin: 10px auto;
  display: flex;
  justify-content: center;
  /* align horizontal */
}
.left {
  width: 69%;
  max-width: 350px;
  background: blue
}
.right {
  width: 29%;
  max-width: 150px;
  background: red
}
.box {
  float: left;
  padding: 20px
}
<div class="wrapper">
  <div class="container">
    <div class="left box">Content</div>
    <div class="right box">Content</div>
  </div>
</div>

关于html - 居中一个没有设置宽度的div容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26970488/

相关文章:

javascript - 如何使用 javascript 隐藏表格的单元格

javascript - 如何在鼠标悬停时更改 setInterval() 回调函数不断修改的元素的值?

html - 将类添加到父 DIV 时更改 DIV CSS 属性?

css - 使用 R 从网站的表格中抓取数据

javascript - 按类对 li 元素进行排序? jQuery/Javascript

html - 页脚问题后的空白

html - 图像在浏览器调整大小时重叠。如何将它们隔开?

jquery - 将 Bootstrap 3.0 Navbar 默认调整大小更改为自定义调整大小

jquery - 一个ID只能用一次,什么意思?

html - 使用 Bootstrap 防止缩放缩放