css3 如何垂直居中对齐

作者: guiLing | 来源:发表于2016-10-21 10:44 被阅读79次
方案1 (需要使用绝对定位)
<div id="box">未知宽高垂直居中</div>
<style type="text/css">
#box{
    position: absolute;
    background: #f60;
    padding: 20px;
    border: 2px solid#ccc;
    left: 50%;top: 50%;
    transform: translate(-50%,-50%);
    transformstyle:preserve-3d;
    color: #fff;
    line-height: 180%;
}
</style>
方案2 (它只适用于在视口中居中的场景,不适用在标签中嵌套场景下)
<div id="box">未知宽高垂直居中<br></div>
<style type="text/css">
#box{
    width: 18em;
    padding: 1em 1.5em;
    -margin: 50vh auto 0;
    transform: translateY(-50%);
}
</style>
方案3 (完美解决方案)

关键步骤: 给父元素添加 display: flex 子元素添加 margin: auto;

<div id="parent">
    <div id="child">未知宽高垂直居中</div>
</div>
<style type="text/css">
#parent{
    display: flex;
    min-height: 100vh;
}
#child{
    display: flex;
    align-items: center;
    justify-content: center;
    width: 18em;
    height: 10em;
    background: #f60;
    margin: auto;
}
</style>

相关文章

网友评论

本文标题:css3 如何垂直居中对齐

本文链接:https://www.haomeiwen.com/subject/tngquttx.html