我有2个div,彼此相邻,我使用flex和justify-content/align-items垂直和水平居中。
例子
HTML:
<div class="inner">
<div class="section green">
<img src="http://i.imgur.com/hEOMgVf.png">
</div>
<div class="section red">
<img src="http://i.imgur.com/nEybO1g.png">
</div>
</div>
CSS:
.inner {
float: left;
width: 500px;
display: flex;
justify-content: center;
align-items: center;
background-color: #343434;
text-align: center;
}
.section {
float: left;
flex: 1;
}
.green { background-color: #7dc242; }
.red { background-color: #ed1c24; }
我的问题是,我需要将两个“section” div的高度设置为相同的高度,并将其垂直和水平居中。您可以在下面的JSFiddle中看到,绿色背景与红色背景的高度不同。如何使两个div都达到容器div的整个高度?
这是我所拥有的简化的JSFiddle:
http://jsfiddle.net/beK28/1/
最佳答案
为了获得想要的效果,您不应尝试在容器元素中进行任何对齐,而应将.section
设置为display:flex
。然后,您可以在子元素中正确地对齐图像并将其居中。
.section {
align-items: center;
display: flex;
flex: 1;
justify-content:center;
text-align: center;
}
http://jsfiddle.net/beK28/8/
您也不需要使用float,这就是使用灵活容器的全部要点。