方法二有点难理解,能解释一下原理吗

来源:2-14 编程练习

谷谷3

2019-04-22 22:56:31

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    *{
      margin: 0;
      padding:0;
    }
    .test{
     width: 800px;
     height: 100px;
     background: red;
     position:fixed;
     left:50%;
     margin-left:-400px; /*方法二*/
     
     /*top:0px;
     left:0px;
     right:0px;
     bottom:0px;
     margin:0 auto;    方法一*/
   
   }
   .out{
    width: 100%;
    height: 8000px;
    background-color: #abcdef;
  }
</style>
</head>
<body>
  <div class="out">
    <div class="test"></div>
  </div>
</body>
</html>


写回答

1回答

樱桃小胖子

2019-04-23

第二种方法叫做“拔河效应”,拔河效应简单理解如下:

left:0把元素向左侧拉,right:0把元素向右侧拉,left和right的值都为0,相当于是作用在元素上的左右两侧拉力相同,那么元素就会即不会偏向左边,也不会偏向右边,而是处于中间位置,垂直居中也是一样的道理,top:0把元素向上拉,bottom把元素向下拉,top和bottom的值都为0,相当于是作用在元素上的上下两侧拉力相同,那么元素就即不会向上偏移也不会向下偏移,而是处于中间位置。类似于小时候玩过的拔河游戏。

希望可有帮到你!

0

0 学习 · 40143 问题

查看课程