问题
I need to center a div in flex container with keeping the height of the whole container for that div. Obviously, I have align-items:stretch for keeping a height or align-items:center for centering block. What is a good approach for flexbox model to center a div with keeping height of the parent container?
JSFiddle: http://jsfiddle.net/symb8s02/
回答1:
You could wrap the text node with a span element and then set the display of .child2 to flex and add align-self: center to the child span element for vertical centering.
Updated Example
.child2 {
border-left: 1px black solid;
align-self: stretch;
display: flex;
}
.child2 > span {
align-self: center;
}
.container {
display: flex;
justify-content: space-between;
align-items: center;
background-color: yellow;
}
.child1 {
background-color: green;
}
.child2 {
border-left: 1px black solid;
align-self: stretch;
display: flex;
}
.child2 > span {
align-self: center;
}
<div class="container">
<div class="child1">
<h1>Text</h1>
</div>
<div class="child2">
<span>should be centered vertically</span>
</div>
</div>
来源:https://stackoverflow.com/questions/28929635/center-div-vertically-in-flexbox-container-with-stretch-alignment