首页 > 解决方案 > CSS垂直对齐图像不适用于display flex

问题描述

所以我有这个 HTML 布局:

<div class="container" style="height: 170px;">

<div class="wrapper">
    <div class="banner">
        <img class="logo" src="myimage.png">
    </div>
</div>

</div>

我在 wrapper 类上使用 display flex,我试图垂直居中对齐,我尝试使用 align-content 和 justified-content,但我的徽标要么停留在 div 的顶部,要么被拉伸...这是我的CSS代码:

.wrapper {
    background: url(banner.jpg) no-repeat center center;
    background-size: cover;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    width: 100%;
    max-width: 100%;
    height: 100%;
}

.banner {
    text-align: center;
    width: 50%;
    /* filter: drop-shadow( 15px 15px 15px rgba(0, 0, 0, 1.00)); */
    padding: 0px 5% 0px 5%;
    background-color: rgba(0, 0, 0, 0.67);
    background-color: rgba(0, 0, 0, 0.67);
    height: 100%;
}

.logo {
    margin-top: 20px;
    max-width: 100%;
    max-height: 130px;
    margin-bottom: 20px;
}

标签: htmlcss

解决方案


flexbox 仅适用于直接子级,因此要使其正常工作,height: 100%请从子级 ( .banner) 中删除,如下所示:

.banner {
    text-align: center;
    width: 50%;
    /* filter: drop-shadow( 15px 15px 15px rgba(0, 0, 0, 1.00)); */
    padding: 0px 5% 0px 5%;
    background-color: rgba(0, 0, 0, 0.67);
}

或将 flexbox 参数也添加到子项 ( .banner) 并删除text-align(因为不再需要),如下所示:

.banner {
    width: 50%;
    /* filter: drop-shadow( 15px 15px 15px rgba(0, 0, 0, 1.00)); */
    padding: 0px 5% 0px 5%;
    background-color: rgba(0, 0, 0, 0.67);
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}

推荐阅读