【问题标题】:Centering content horizontally using flexbox [duplicate]使用flexbox水平居中内容[重复]
【发布时间】:2017-03-30 14:35:12
【问题描述】:
我正在努力将容器中的一些内容水平居中:
https://jsfiddle.net/y56t31q9/6/
.container {
display: flex;
flex-direction: column;
width: 600px;
background-color: blue;
justify-content: center;
/* Not centering content horizontally? */
}
.item {
max-width: 500px;
height: 100px;
background-color: yellow;
border: 2px solid red;
}
<div class="container">
<div class="item"></div>
<section class="item"></section>
<section class="item"></section>
<footer class="item"></footer>
</div>
我原以为 justify-content 会成功,但无济于事。
任何帮助将不胜感激
谢谢!
【问题讨论】:
标签:
html
css
alignment
flexbox
【解决方案1】:
添加align-items:center;
.container {
display: flex;
flex-direction: column;
width: 600px;
background-color: blue;
justify-content: center;
align-items:center;
}
【解决方案2】:
justify-content:center 属性沿 flex 方向对齐 flex-items - 使用 align-items:center- 参见下面的演示:
.container {
display: flex;
flex-direction: column;
width: 600px;
background-color: blue;
justify-content: center;
align-items:center;/*NEW*/
}
.item {
max-width: 500px;
width: 250px;/*NEW*/
height: 100px;
background-color: yellow;
border: 2px solid red;
}
<div class="container">
<div class="item"></div>
<section class="item"></section>
<section class="item"></section>
<footer class="item"></footer>
</div>
参考:Flexbox W3C spec
以下是flex-direction 为行时适用的图像:
一个。主轴对齐:justify-content
b.跨轴对齐:align-items
当flex-direction为row时,主轴是水平的,但当它是column时,则相反。
【解决方案3】:
删除flex-direction:column 和max-width:500px。
给一些固定的宽度,比如 100px,它会正常工作。如果你使用flex-direction:column,使用align-items:center属性水平居中,justify-center如果是row。