各种居中的css实现

来源:互联网 发布:如何注销淘宝账号 编辑:程序博客网 时间:2024/06/06 06:47

一、文本居中

  文本的水平居中text-align:center;

  文本的垂直居中设置行高即可line-height:20px;

二、行内元素的居中

vertival-align是相对兄弟的行高来定位,所有加一个空的兄弟使得高度等于父盒子

    #box{        width: 800px;        height: 800px;        border: 1px solid red;        text-align: center;    }    img{        vertical-align: middle;    }    #block{        height:100%;//和父盒子一样高    }<div id='box'>  <img src='a.png'>  <img id='block'></div>

三、盒子的居中方法

1.text-align实现水平居中

text-align用于设置盒子的内容水平居中(文本属性,子盒子可继承),要设置子盒子水平居中,设置display:inline-block;

    #box{        width: 400px;        height: 400px;        border: 1px solid red;        text-align: center;    }    #child{        width: 50px;        height: 50px;        border: 1px solid blue;        display: inline-block;    }

2.margin:0 auto;设置水平居中

使用注意点:盒子不能浮动,盒子要有宽度

3.绝对定位实现垂直水平居中,要知道宽高

先用top:50%;left:50%;将盒子左上角放在父盒子中心点,在用负margin将子盒子向上拉一半,向左拉一半

    #box{        width: 400px;        height: 400px;        border: 1px solid red;        position: relative;    }    #child{        width: 50px;        height: 50px;        border: 1px solid blue;        position: absolute;        top: 50%;        left: 50%;        margin-top:-25px;        margin-left: -25px;    }

4.flex,最简单

    #box{        width: 400px;        height: 400px;        border: 1px solid red;        display: flex;        /*水平居中*/        justify-content:center;        /*垂直居中*/        align-items:center;    }    #child{        width: 50px;        height: 50px;        border: 1px solid blue;    }

5.transform,类似负margin拉回元素,不过不需要居中元素的宽高

    #box{        height: 400px;        border: 1px solid red;        position: relative;    }    #child{        border: 1px solid blue;        position: absolute;        top: 50%;        left:50%;        transform:translate(-50%,-50%);//相对于居中元素    }

6.无视居中元素的宽高

    #box{        height: 400px;        border: 1px solid red;        position: relative;    }    #child{        width: 50px;        height: 50px;        border: 1px solid blue;        position: absolute;        top:0;        left: 0;        right: 0;        bottom: 0;        margin:auto;    }
原创粉丝点击