水平垂直居中的四种方法

版权声明:哼!坏人!这是我辛辛苦苦码的! https://blog.csdn.net/DurianPudding/article/details/87947530
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>水平垂直居中</title>
  <style>
    .color {
      width: 200px;
      height: 200px;
      background-color: #555555;
    }
    .center {
      width: 100px;
      height: 100px;
      background-color: black;
    }

    .container1 {
      position: relative;
    }
    .container1 .center {
      position: absolute;
      /*
      原点位置在元素的左上角!!!!
      距离上侧50%,距离左侧50%;
      此例向右移动,向下移动,相当于移到了第二象限,左上角是原点
      */
      top: 50%;
      left: 50%;
      /*
      2D移动,第一个参数是x轴,正向水平向右;第二个参数是y轴,正向垂直向下;原点位置在元素的正中心!!!
      此例向左移动,向上移动
       */
      transform: translate(-50%, -50%);

    }

    .container2 {
      position: relative;
    }
    .container2 .center {
      position: absolute;
      top: 50%;
      left: 50%;
      /*
      绝对定位中,真正移动的top值是top和marin-top的叠加
      此时先移动父元素长度的50%,再根据中间块的长度移动。这样如果父元素大小改变,中间块仍然居中。
      所以不能直接写 top: 50px; left: 50px;
       */
      margin: -50px 0 0 -50px;
    }

    .container3 {
      position: relative;
    }
    .container3 .center {
      position: absolute;
      margin: auto;

      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
    }

    .container4 {
      display: flex;
      /*
      注意这两行是写在父元素里呀
       */
      justify-content: center;
      align-items: center;
    }
  </style>
</head>
<body>
<h2>水平垂直居中</h2>
<h4>一、使用absolute和translate</h4>
<p>注意绝对定位移动时,原点位置在 左上角;</p>
<p>而 translate 移动时,原点位置在 元素正中心。且y轴正向垂直向下</p>
<div class="container1 color">
  <div class="center"></div>
</div>

<h4>二、使用absolute 和 margin(自身)</h4>
<p>
  绝对定位中,真正移动的top值是top和marin-top的叠加
</p>
<p>结合使用absolute和margin:此时先移动父元素长度的50%(absolute),再根据中间块的长度(margin)移动。这样如果父元素大小改变,中间块仍然居中。
  所以不能直接写 top: 50px; left: 50px;</p>
<div class="container2 color">
  <div class="center"></div>
</div>

<h3>三、使用absolute 和 margin(auto)</h3>
<p>使用绝对定位,离上下左右多远(此题都设0),然后让margin自动填充</p>
<div class="container3 color">
  <div class="center"></div>
</div>

<h3>四、使用flex</h3>
<p>父元素flex布局,并设置justify-content: center; align-items: center; 不要写在中间块啊,是父元素啊</p>
<div class="container4 color">
  <div class="center"></div>
</div>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/DurianPudding/article/details/87947530