CSS的5种垂直和水平居中方式

1.使用position定位+margin:auto

父级元素相对定位,子元素绝对定位,子元素四边都设置为0

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
    .box{
        margin: 0 auto;
        height: 600px;
        width: 600px;
        background-color: #666;
        position: relative;
       
    }
    .dv{
        height: 200px;
        width: 200px;
        background-color: deepskyblue;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        margin: auto;    
    }        
    </style>
</head>
<body>
    <div class="box">
        <div class="dv"></div>
    </div>
</body>
</html>

在这里插入图片描述

2.使用position定位+margin-left/right/top/bottom

如果需定位的元素宽高已知,先设父元素为相对定位,子元素为绝对定位。把位置先定到宽高的50%,再用margin-top/left/bottom/right,值为自身一半的负数。

html:  
<div class="box">
        <div class="dv"></div>
    </div>
css:
  .box{
        margin: 0 auto;
        height: 600px;
        width: 600px;
        background-color: #666;
        position: relative;
    }
    .dv{
        position: absolute;
        height: 200px;
        width: 200px;
        top: 50%;
        left: 50%;
        margin-top: -100px;
        margin-left: -100px;
        background-color: deepskyblue;    
    } 

3.用position定位+translate位移

这是在未知元素宽高时的用的居中方式,因为tranlate的值用百分比表示时,位移距离的是自身宽高的百分比的值。所以可以在1的基础上把marginmargin-top/left/bottom/right改成transform:translate(xxx%,xxx%)。

  .dv{
        position: absolute;
        height: 200px;
        width: 200px;
        top: 50%;
        left: 50%;
        /* margin-top: -100px;
        margin-left: -100px; */
        transform: translate(-50%,-50%);
       
        background-color: deepskyblue;    
    }        

4.在弹性盒子中的居中

首先把盒子的display设置为flex,再设置垂直和水平居中,只需修改父级元素的属性值即可,

这是我个人比较喜欢的居中方式。

   .box{
        margin: 0 auto;
        height: 600px;
        width: 600px;
        background-color: #666;
        display: flex;
        justify-content: center;
        align-items: center;       
    }
    .dv{
        height: 200px;
        width: 200px;     
        background-color: deepskyblue;    
    }        

5.在网格布局中的居中

这与在弹性盒子的居中方式很类似,也是在父级元素上设置display:grid,再设置居中即可,也是只需修改父级元素属性值。

.box{
        margin: 0 auto;
        height: 600px;
        width: 600px;
        background-color: #666;
        /* display: flex;
        justify-content: center;
        align-items: center; */
        display: grid;
        justify-items: center;
        align-items: center;
       
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值