美文网首页
垂直居中方法总结

垂直居中方法总结

作者: 不扎人的大刺猬 | 来源:发表于2019-01-18 17:43 被阅读0次

    一直想要梳理总结一遍,今天终于开了头,文章会不定期更新,本人前端小白,有不正确的地方,欢迎大佬指正

    目前先总结了7种垂直居中方法,有更简单的好用的会持续更新,敬请关注

    第一:设置line-height

    <div class="box1">

            <span class="content">垂直居中</span>

        </div>

    .box1 {

            width: 300px;

            height: 300px;

            border: 1px solid red;

            line-height: 300px;

        }

    第二:绝对定位和相对定位

    .box1{

            width: 300px;

            height: 300px;

            border: 1px solid red;

            position: relative;

        }

        .content{

            position: absolute;

            top:50%;

            transform: translate(0,-50%);

            /* margin-top:-10.5px; */  或者查看子元素的高度,都可以实现垂直居中,这里span的高度是21px,

        }

    第三:vertical-align

    .box1{

            width: 300px;

            height: 300px;

            border: 1px solid red;

            display: table-cell;

            vertical-align: middle;

        }

    第四:flex

    .box1{

            width: 300px;

            height: 300px;

            border: 1px solid red;

            display: flex;

            align-items: center;

        }

    第五:利用伪元素

    .box1{

            width: 300px;

            height: 300px;

            border: 1px solid red;

    }

    .box1 span{

      vertical-align:middle;

      display:inline-block;

      font-size:16px;

    }

    .box1:after{

      content:'';

      width:0;

      height:100%;

      display:inline-block;

      vertical-align:middle;

    }

    第六:依然flex布局

    .box1{

        width: 300px;

            height: 300px;

            border: 1px solid red;

        display: flex;

    }

    .content{

        margin:auto 0;

    }

    第七:

    .box1{

        width: 300px;

            height: 300px;

            border: 1px solid red;

        display: -webkit-box;

        -webkit-box-pack:center;

        -webkit-box-orient: vertical;

    }

    相关文章

      网友评论

          本文标题:垂直居中方法总结

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