我试图在另一个div元素中垂直居中一个span或div元素。然而,当我输入vertical-align: middle时,什么都没有发生。我试着改变这两个元素的显示属性,但似乎都不起作用。
这是我目前在我的网页上做的事情:
.main {
身高:72 px;
vertical-align:中间;
边框:1px纯黑色;
填充:2 px;
}
在{
vertical-align:中间;
边框:1px纯红色;
}
接着{
边框:1px纯蓝色;
}
< div class = "主" >
< div class = "内部" >
这个盒子应该放在大盒子的中间
<div class="second">这里还有一个盒子</div>
< / div >
< / div >
下面是实现的jsfiddle,显示它不起作用:http://jsfiddle.net/gZXWC/
这里是最新的最简单的解决方案-不需要改变任何东西,只需添加三行CSS规则到您的div的容器中,您希望居中。我爱FlexBox #爱Flex xbox
.main {
/* I changed height to 200px to make it easy to see the alignment. */
height: 200px;
vertical-align: middle;
border: 1px solid #000000;
padding: 2px;
/* Just add the following three rules to the container of which you want to center at. */
display: flex;
flex-direction: column;
justify-content: center;
/* This is true vertical center, no math needed. */
}
.inner {
border: 1px solid #000000;
}
.second {
border: 1px solid #000000;
}
<div class="main">
<div class="inner">This box should be centered in the larger box
<div class="second">Another box in here</div>
</div>
<div class="inner">This box should be centered in the larger box
<div class="second">Another box in here</div>
</div>
</div>
奖金
justify-content值可以设置为以下几个选项:
flex-start, which will align the child div to where the flex flow starts in its parent container. In this case, it will stay on top.
center, which will align the child div to the center of its parent container. This is really neat, because you don't need to add an additional div to wrap around all children to put the wrapper in a parent container to center the children. Because of that, this is the true vertical center (in the column flex-direction. similarly, if you change the flow-direction to row, it will become horizontally centered.
flex-end, which will align the child div to where the flex flow ends in its parent container. In this case, it will move to bottom.
space-between, which will spread all children from the beginning of the flow to the end of the flow. If the demo, I added another child div, to show they are spread out.
space-around, similar to space-between, but with half of the space in the beginning and end of the flow.