实现垂直/水平居中 (4种)

1.   定位 + 负外边距

原理:元素设置定位并给定 50% 的top值和left值,再通过 负margin 将元素向左上移动自身宽高的一半,要知道子元素的宽度和高度 。

  <style>
    .father{
+     position:relative;   // 绝对定位
      width: 200px;
      height: 200px;
      background-color: pink;
    }
    .son{
+     position: absolute;   // 相对定位
+     top: 50%;
+     left: 50%;
      width: 60px;
      height: 60px;
+     margin-left: -30px;  
+     margin-top: -30px;
      background-color: skyblue;
    }
  </style>

<body>
  <div class="father">
    <div class="son"></div>
  </div>
</body>

2.  定位 + 平移

原理:使用CSS3新增属性 transform 中的 translate 平移属性,根据自身尺寸进行移动,缺点是由于为新增属性,兼容性自然就不是很好,远古IE不支持。

<style>
    .father{
      position:relative;   // 绝对定位
      width: 200px;
      height: 200px;
      background-color: pink;
    }
    .son{
      position: absolute;   // 相对定位
      top: 50%;
      left: 50%;
+     transform: translate(-50%,-50%);  // 2D转换,平移
      width: 60px;
      height: 60px;
      background-color: skyblue;
    }
  </style>

<body>
  <div class="father">
    <div class="son"></div>
  </div>
</body>

3.   margin:auto

原理:该方法的关键点是:1.绝对定位的(top、right、bottom、left)四个属性均要设置值为0;2.margin:auto,能够适用单个元素或者父子级元素,设置绝对定位并添加 margin:auto 属性就能够实现水平垂直居中,元素可自定义宽高,也可不设置(需要是自身存在尺寸的元素:img等)

<style>
    .father{
      position:relative;   // 绝对定位
      width: 200px;
      height: 200px;
      background-color: pink;
    }
    .son{
      position: absolute;   // 相对定位
+     top: 0;
+     bottom:0;
+     left: 0;
+     right: 0;
+     margin: auto; 
      width: 60px;
      height: 60px;
      background-color: skyblue;
    }
  </style>

<body>
  <div class="father">
    <div class="son"></div>
  </div>
</body>

4.  flex布局

原理:通过给父元素设置display为flex,再设置 item 的主轴和辅轴的对齐方式,兼容性也不是很好(IE8+ 及大众浏览器),大多数用于移动端布局

<style>
    .father{
+     display: flex;  // flex布局
+     justify-content: center;  // 定义了项目在主轴上的对齐方式。
+     align-items: center;   // 定义了项目在侧轴上的对齐方式。
      width: 200px;
      height: 200px;
      background-color: pink;
    }
    .son{
      width: 60px;
      height: 60px;
      background-color: skyblue;
    }
  </style>

<body>
  <div class="father">
    <div class="son"></div>
  </div>
</body>

<style>
    .father{
+     display: flex;  // flex布局
      width: 200px;
      height: 200px;
      background-color: pink;
    }
    .son{
+     margin: auto;      
      width: 60px;
      height: 60px;
      background-color: skyblue;
    }
  </style>

<body>
  <div class="father">
    <div class="son"></div>
  </div>
</body>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值