如何在容器中使用flexbox水平和垂直地居中div。在下面的例子中,我想要每个数字都在对方下面(在行中),这是水平居中。

.flex-container { padding: 0; margin: 0; list-style: none; display: flex; align-items: center; justify-content: center; } row { width: 100%; } .flex-item { background: tomato; padding: 5px; width: 200px; height: 150px; margin: 10px; line-height: 150px; color: white; font-weight: bold; font-size: 3em; text-align: center; } <div class="flex-container"> <div class="row"> <span class="flex-item">1</span> </div> <div class="row"> <span class="flex-item">2</span> </div> <div class="row"> <span class="flex-item">3</span> </div> <div class="row"> <span class="flex-item">4</span> </div> </div>

http://codepen.io/anon/pen/zLxBo


当前回答

如果你需要在链接中居中显示文本,这可以做到:

div { 显示:flex; 宽度:200 px; 身高:80 px; 背景颜色:黄色; } 一个{ 显示:flex; 对齐项目:中心; justify-content:中心; text-align:中心;/*只对多行重要*/ 填充:0 20px; 背景颜色:银色; 边框:2px纯蓝色; } < div > 文本< a href = " # " > < / > <a href="#">文本与两行</a> < / div >

其他回答

如果你需要在链接中居中显示文本,这可以做到:

div { 显示:flex; 宽度:200 px; 身高:80 px; 背景颜色:黄色; } 一个{ 显示:flex; 对齐项目:中心; justify-content:中心; text-align:中心;/*只对多行重要*/ 填充:0 20px; 背景颜色:银色; 边框:2px纯蓝色; } < div > 文本< a href = " # " > < / > <a href="#">文本与两行</a> < / div >

Add

.container {
    display: flex;
    justify-content: center;
    align-items: center;
}

到你想居中的容器元素。文档: justify-content和 对齐项目。

用这个:

   html, body {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;
   }

像这样的HTML标记:

   <html>
      <body>
        <main>
          <button> abc </button>
          <p> something </p>
        </main>
      </body>
    </html>

Html, body { 显示:flex; 对齐项目:中心; justify-content:中心; 高度:100%; } < html > 身体< > <大> <button> ABC </button> <p> something </p> 主> < / 身体< / > < / html >

还:flex;对于它的容器和边缘:auto;因为它的项目工作完美。

注意:你必须设置宽度和高度才能看到效果。

#{容器 宽度:100%;/*宽度需要设置*/ 身高:150 px;/*高度需要设置*/ 显示:flex; } .item { 保证金:汽车;/*这些将使项目在中心*/ background - color: # CCC; } < div id = "容器" > 中心< div class = "项目" > < / div > < / div >

你可以利用

display: flex;
align-items: center;
justify-content: center;

在父组件上