Center div vertically in flexbox container with stretch alignment

人走茶凉 提交于 2020-01-01 18:53:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!