面试--css实现元素的水平和垂直居中

针对单行文本

使用line-height

  .wrap{
        width: 200px;height: 200px;background: yellow;
    }
    .wrap span{
        line-height: 200px ;text-align: center;
    }
<div class="wrap">
     <span>sasas</span>
</div>

针对已知高度的块级元素

相对+绝对+margin-top:-height/2+margin-left:-width:-width/2

针对行内块元素实现处置居中

.wrap{
        width: 200px;height: 200px;background: yellow;
    }
    .wrap img{
        vertical-align:middle;text-align: center;
    }
    .wrap .block{
        height: 100%;width: 0;
    }
<div class="wrap">
     <img src="timg.jpg" width="50">
     <img class="block">
</div>

vertical-align:vertical 属性是针对兄弟级别的元素设置的
其中.block也可以使用 img:after或者:before来代替

针对父元素和子元素的高度都未知情况下 定位+transform

 .wrap{
        width: 200px;height: 400px;background: yellow;position: relative;
    }
    .wrap div{
        position: absolute;
        top:50%;left: 50%;transform: translate(-50%,-50%);background: red;
    }
<div class="wrap">
        <div >
            <p>sasas</p>
            <p>sasas</p>
            <p>sasas</p>
            <p>sasas</p>
        </div>
</div>

针对父元素和子元素的高度都未知情况下 父:text-align:center+表格布局 子:vertical-align:middle+表格布局

  .wrap{
        width: 200px;height: 400px;background: yellow;display: table;text-align: center;
    }
    .wrap div{
        display: table-cell;vertical-align:middle;
    }
    <div class="wrap">
        <div >
            <p>sasas</p>
            <p>sasas</p>
            <p>sasas</p>
            <p>sasas</p>
        </div>
</div>

针对父元素高度但是子元素的高度已知都未知情况下 父:相对定位 子:绝对定位+四个属性都为0 +margin:auto

 .wrap{
        width: 200px;height: 400px;background: yellow;
        position: relative;
    }
    .wrap div{
        width:20px;height:100px;position: absolute;top:0;left: 0;right: 0;bottom: 0;margin: auto;
        background: red;
    }
    <div class="wrap">
        <div >
            <p>sasas</p>
            <p>sasas</p>
            <p>sasas</p>
            <p>sasas</p>
        </div>
</div>

使用flex布局

  .wrap{
        width: 200px;height: 400px;background: yellow;
        position: relative;
        display: flex; justify-content: center; flex-direction: column;
    }
    .wrap div{
        width:20px;top:0;left: 0;right: 0;bottom: 0;margin: auto;
        background: red;
    }
    <div class="wrap">
        <div >
            <p>sasas</p>
            <p>sasas</p>
            <p>sasas</p>
            <p>sasas</p>
        </div>
</div>
    原文作者:丹丹赵
    原文地址: https://segmentfault.com/a/1190000010913046
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞