纯CSS实现垂直水平居中的5种方式

1.绝对定位+margin:auto+left: 0; right: 0; top: 0; bottom: 0;

css部分

<style type="text/css">
    .wrp {
        background-color: #b9b9b9;
        width: 240px;
        height: 160px;
        position: relative; 
    }
    .box{
        color: #fff;
        background-color: #3e8e41;
        width: 200px;
        height: 120px;
        margin: auto;
        position: absolute;
        left: 0; right: 0; top: 0; bottom: 0;
    }
    </style>

页面布局


<div class="wrp">
    <div class="box">
        <p>我是大美女</p> 
    </div>
</div>

效果:
这里写图片描述

2、绝对定位+margin反向偏移

<style type="text/css">
    .wrp {
        background-color: #b9b9b9;
        width: 240px;
        height: 160px;
        position: relative; 
    }
    .box{
        color: #fff;
        background-color: #3e8e41;
        width: 200px;
        height: 120px;
        position: absolute;
        top: 50%; left: 50%;
        margin-left: -100px; /* (width + padding)/2 */
        margin-top: -60px; /* (height + padding)/2 */

    }
    </style>

布局:

<div class="wrp">
    <div class="box">
        <p>我是大美女</p> 
    </div>
</div>

效果:
这里写图片描述

3.绝对定位+transform反向偏移

<style type="text/css">
    .wrp {
        background-color: #b9b9b9;
        width: 240px;
        height: 160px;
        position: relative; 
    }
    .box{
        color: #fff;
        background-color: #3e8e41;
        width: 200px;
        height: 120px;
        position: absolute;
        top: 50%; left: 50%;
        -webkit-transform: translate(-50%, -50%);
        -ms-transform: translate(-50%, -50%);
        transform: translate(-50%, -50%);
    }

    </style>

布局:

<div class="wrp">
    <div class="box">
        <p>我是大美女</p> 
    </div>
</div>

效果:
这里写图片描述

4.display:tabel

css部分:

<style>
    /*** .table和.cell都将撑满页面,cell的子元素水平垂直居中 ***/
    .table{
        display: table;
        width: 200px;
        height: 200px;
    }
    .cell {
        display: table-cell;
        vertical-align: middle;
        text-align: center;
        border: 1px solid #666;
    }
    </style>

布局:

<div class="table">
    <div class="cell">
       <p>我爱你,我爱你</p>
       <p>我爱你,我爱你</p>   
    </div>
</div>

效果:

这里写图片描述

5、display: flex

<style>
    .flex{
        display: flex;
        width: 200px;
        height: 200px;background: #ccc;
        justify-content:center;
         align-items: center;
    }
    .box {
        background: red;
        height: 50px;
        width:100px;
        color:#fff;
    }
    </style>

布局:

<div class="flex">
    <div class="box">
       我是大美女
    </div>
</div>

效果:
这里写图片描述

可能还有其他方式,之后再做补充!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值