Skip to content

Latest commit

 

History

History
85 lines (80 loc) · 1.48 KB

垂直居中.md

File metadata and controls

85 lines (80 loc) · 1.48 KB

文本垂直居中

  若为单行文本,使用 line-height 设为父元素的高度即可居中。

垂直居中(定高子元素)

<div class="father">
    <div class="child"></div>
</div>

1.margin 设为(父元素高度 - 子元素高度)/2

.father{
    height: 350px;
    width: 350px;
    background-color: red;
    overflow: hidden;
}
.child{
    height: 200px;
    width: 200px;
    background-color: blue;
    margin:75px 0;
}

2.absolute + margin-top: - 子元素高度/2

.father{
    height: 350px;
    width: 350px;
    background-color: red;
    position: relative;
}
.child{
    height: 200px;
    width: 200px;
    background-color: blue;
    position: absolute;
    top: 50%;
    margin-top: 100px;
}

垂直居中(不定高子元素)

3.思路同 2 ,利用 transform 属性

.father{
    height: 350px;
    width: 350px;
    background-color: red;
    position: relative;
}
.child{
    height: 200px;
    width: 200px;
    background-color: blue;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
}

4.三层元素法,需要建立 new-child 子元素,本质上同 2

.father{
    height: 350px;
    width: 350px;
    background-color: red;
    position: relative;
}
.child{
    height: 200px;
    width: 200px;
    position: absolute;
    top: 50%;
}   
.new-child{
    height: 200px;
    width: 200px;
    background-color: blue;
    position: relative;
    bottom: 50%;
}