HTML5+CSS3-基础09-水平&垂直居中

HTML5+CSS3-基础09-水平&垂直居中

直接上代码

<!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>
    .father {
      width: 1000px;
      height: 1000px;
      background-color:green;
      position: relative;
    }

    .son {
      width: 150px;
      height: 150px;
      background-color: skyblue;
      line-height: 150px;
      text-align: center;
      color: #fff;
    }

    /* 定位1 (需要知道盒子的自身高度和宽度)*/
    /* .son {
      position: absolute;
      top: 50%;
      left: 50%;
      margin-top: -50px;
      margin-left: -50px;
    } */


/* 定位2 (盒子需要高度和宽度)*/
    /* .son{
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      margin: auto;
    } */

    /* 定位3 (兼容性不好)*/
    /* .son{
      position: absolute;
      top: 50%;
      left: 50%;
      
      transform: translate(-50%, -50%);
    } */

    /* 4.利用display:flex布局 */
    /* .father{
      display: flex;
      align-items: center;
      justify-content: center;
    } */

    /* 5.需要父盒子有固定宽高 */
    .father{
      display: table-cell;
      vertical-align: middle;
      text-align: center;

    }
    .son{
      display: inline-block;
    }
  </style>
</head>

<body>
  <div class="father" id="father">
    <div class="son" id="son">水平/垂直居中</div>
  </div>
  <!-- js方法 -->
<script>
  // winW = father.offsetWidth;
  // winH = father.offsetHeight;
  // sonW = son.offsetWidth;
  // sonH = son.offsetHeight;
  // son.style.position = "absolute";
  // son.style.left = (winW - sonW) / 2 + "px";
  // son.style.top = (winH - sonH) / 2 + "px";

</script>
</body>

</html>

内容仅供学习参考,若有错误欢迎大家指正----WUCASE

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值