CSS水平垂直居中

水平居中:
(1)行内元素:text-align:center;
(2)块级元素:margin:auto;
(3)定位元素:left:50%+margin-left:负(自身宽度的一半);
(4)flex布局:justify-content:center;
垂直居中:
(1)行内元素:line-height属性值等于height值。
(2)定位元素:top:50%;+margin-top:负(自身高度的一半);
(3)绝对定位+平移(不需知道元素高度);

.father {
         width: 200px;
         height: 200px;
         background-color: rgb(20, 221, 228);
         position: relative;
     }
        
.son {
      background-color: rgb(99, 211, 48);
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      margin: 0px;
  }

  <!-- 1.不能确定元素高度 -->
<div class="father">
   <p class="son">垂直居中</p>
</div>

(4)绝对定位元素:top,left,right,bottom均设置为0,+margin:auto;(不需要确定元素高度)
在这里插入图片描述

.father2 {
            width: 200px;
            height: 200px;
            background-color: rgb(34, 20, 228);
            position: relative;
        }
        
    .son2 {
         background-color: rgb(99, 211, 48);
         position: absolute;
         height: 30px;
         width: 100px;
         top: 0;
         right: 0;
         bottom: 0;
         left: 0;
         /* !!!margin */
         margin: auto;
     }
 <div class="father2">
        <p class="son2">垂直居中</p>
 </div>

(5)flex布局(不需要确定元素高度)

 .father3 {
            width: 200px;
            height: 200px;
            background-color: rgb(20, 221, 228);
            display: flex;
            align-items: center;
        }
        
        .son3 {
            background-color: rgb(99, 211, 48);
        }
		<div class="father3">
		        <p class="son3">垂直居中</p>
		</div>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值