温故而知新之CSS篇-盒子水平垂直居中的方法

盒子水平垂直居中的方法
(1)使用定位的方法(三种方法):
第一种方法:(已知盒子的宽高,需要计算盒子的宽高)

<body>
    <div class="father">
      <div class="son">儿子</div>
    </div>
</body>
<style>
      .father{
        position: relative;
        /* 这一步是为了让son基于father定位 */
        width: 500px;
        height:300px;
        border: 1px solid blue;  
      }
      .son{
        position: absolute;
        left: 50%;  
        top: 50%;
        /* 到这一步为止,son的左上角是在father里面垂直居中的 */
        margin-left: -100px; 
        margin-top: -50px;
        /* 这里是为了让son的中心位置在father中垂直居中,所以取了son宽高的一半。 */
        width: 200px;
        height: 100px;
        background-color: pink;
      }
    </style>

第二种方法:(盒子必须要有宽高,但是不需要计算宽高)

 .son{
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        margin: auto;
        width: 200px;
        height: 100px;
        background-color: pink;
      }

第三种方法:(不需要知道盒子的宽高)

.son{
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
        background-color: pink;
      }

在这里插入图片描述

(2)使用display:flex的方法:

.father{
        display: flex;
        justify-content: center;
        /* x轴 */
        align-items: center;
        /* y轴 */
        width: 500px;
        height:300px;
        border: 1px solid blue;  
      }
      .son{
        width: 200px;
        height: 100px;
        background-color: pink;
      }

(3)使用JavaScript的方法:

<body>
    <div class="father" id="box">
      js实现垂直居中
    </div>
    <script>
      let HTML = document.documentElement;
      windowW = HTML.clientWidth;
      windowH = HTML.clientHeight;
      boxW = box.offsetWidth;
      boxH = box.offsetHeight;
      console.log(boxH)
      box.style.position = "absolute";
      box.style.left = (windowW-boxW)/2+'px';
      box.style.top = (windowH-boxH)/2+'px';
    </script>
  </body>
  <style>
  body{
        position: relative;
      }
  #box {
        width: 200px;
        height: 100px;
        background-color: pink ;
      }</style>
  • 32
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 21
    评论
评论 21
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值