垂直居中

147 阅读1分钟

1、文本/行内元素/行内块级元素垂直居中(line-height = height)

<div class="parent1">
    <span>垂直居中</span>
</div>
 span {
    display: inline-block;
}
.parent1 {
    height: 200px;
    background: yellow;
    line-height: 200px;
}   

2、单个块级元素垂直居中(定位)

单个块级元素
(1)知道元素高度 .txt1 { width: 100px; height: 100px; position: absolute; background: red; top: 50%; margin-top: -50px; } (2)不知道元素高度

   .txt1 {
    width: 100px;
    height: 100px;
    position: absolute;
    background: red;
    top: 50%;
    transform: translateY(-50%);
   }

(3)特殊的写法(这种不需要考虑宽和高,但是一定得有宽和高)

   .txt1 {
    width: 100px;
    height: 100px;
    position: absolute;
    background: red;
    top: 0;
    bottom: 0;
    margin: auto;
 }

3、多个块级元素垂直居中(flex)

 <div class="parent2">
    <div class="txt2">1</div>
    <div class="txt2">2</div>
    <div class="txt2">3</div>
    <div class="txt2">4</div>
</div>
<style>
.parent2 {
    display: flex;
    align-items: center;
    height: 200px;
    background: yellow;
}
.txt2 {
    width: 100px;
    height: 100px;
    background: red;
    margin-right: 10px;
}
</style>