html - 中心 div 宽度取决于内容

标签 html css centering

我正在尝试实现如下所示的目标:

Goal

我不知道将呈现多少个绿色元素,因为这是由 CMS 以及作者决定在其中放置多少组件决定的。

要求是在换行前每行有5个盒子。

问题是:当我将 red 包装器设置为 inline-block 时,margin: auto 不起作用。

div.container {
  background: black;
  padding: 10px;
}

div.wrapper {
  margin: 0 auto;
  background: red;
  padding: 10px;
  display: inline-block;
}

div.box {
  display: inline-block;
  background: lime;
  padding: 10px;
  margin: 0 10px;
}
<div class="container">
  <div class="wrapper">
    <div class="box">
      Content 1
    </div>
    <div class="box">
      Content 2
    </div>
  </div>
</div>

最佳答案

div.container {
  background: black;
  padding: 10px;
  text-align: center;
}

div.wrapper {
  margin: 0 auto;
  background: red;
  padding: 10px;
  display: inline-block;
}

div.box {
  display: inline-block;
  background: lime;
  padding: 10px;
  margin: 0 10px;
}
<div class="container">
  <div class="wrapper">
    <div class="box">
      Content 1
    </div>
    <div class="box">
      Content 2
    </div>
  </div>
</div>

只需将 text-align center 添加到 div.container

关于html - 中心 div 宽度取决于内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42107855/

相关文章:

html - CSS 颜色不加载按钮

html - 列表内容居中

android - Android 上的 ionic : redirected image sources break ng-src

php - jcarousel 不滚动图像

css - 如何居中固定位置、动态宽度的 div [包括图表]?

html - 如何使包装内的图像跨越包装的整个宽度

html - 如何创建投影?

javascript - 对齐方式的变化?

jquery - 谷歌浏览器中的粘滞条忽略 z-index

PHP : How to change page title of PDF in browser