css布局,居中的方法

关于css居中是前端面试中比较常问的问题之一,以下是我总结的关于css居中的一些方法。
第1种:margin:auto;
把margin设为auto,该方法只能对水平元素进行居中,对浮动元素或绝对定位元素无效。
第2种:text-align:center;
只对行内元素起作用,对块级元素无用。
只能对图片,按钮,文字等行内元素(display:inline或display:inline-block)的元素进行水平居中。
在IE6,IE7这两个浏览器下,对任何元素进行水平居中。
第3种:line-height
使用line-height让单行的文字垂直居中。
将文字的line-height设为文字父容器的高度,适用于只有一行文字的情况。
第4种:
利用css控制表格内容居中:text-align:center; vertical-align:middle
第5种:display:table-cell
对于不是表格的元素,通过display:table-cell将它模拟成一个表格单元格,然后利用表格的居中特性。

上述5种方法都是比较简单的居中方法,那么如何实现让一个div垂直居中?

html代码如下:

<div class="wrapper">
    <div class="content"></div>
</div>

第一种:子元素相对父元素绝对定位水平垂直居中 margin:auto

    .wrapper{
        position:relative;
        width:300px;
        height:300px;
        background:#ff0;
    }
    .content{
        width:100px;
        height:100px;
        background:#f0f;
        position:absolute;
        left:0;
        top:0;
        bottom:0;
        right:0;
        margin:auto;
     }

第二种:子元素相对父元素绝对定位水平垂直居中 margin负间距

   .wrapper{
        width:300px;
        height:300px;
        background:#ff0;
        position:relative;
    }
    .content{
        width:100px;
        height:100px;
        background:#f0f;
        position:absolute;
        top:50%;
        left:50%;
        margin-top:-50px;
        margin-left:-50px;
     }

注意:子元素进行绝对定位,top值和left值均设为50%,margin-top负值,设为子元素高度的50%,margin-left负值,设为子元素宽度的50%。
第三种:子元素相对父元素绝对定位水平垂直居中 transform变形

 .wrapper{
        width:300px;
        height:300px;
        background:#ff0;
        position:relative;
    }
    .content{
        width:100px;
        height:100px;
        background:#f0f;
        position:absolute;
        top:50%;
        left:50%;
        transform:translate(-50%,-50%);
    }

第四种:flex布局

  .wrapper{
        width:300px;
        height:300px;
        background:#ff0;
        display:flex;
        justify-content:center;
        align-items:center;
    }
    .content{
        width:100px;
        height:100px;
        background:#f0f;
    }

justify-content:设置或检索弹性盒子元素在横轴方向上的对齐方式
align-items:设置或检索弹性盒子元素在侧轴方向上的对齐方式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值