如何垂直居中一个浮动元素

<!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>
    /* 已知宽高进行居中 */
    #known {
      position: relative;
      height: 500px;
      background: palegreen;
    }

    #known p {
      width: 200px;
      height: 200px;
      background: orange;
      position: absolute;
      top: 50%;
      left: 50%;
      /* 二分之一的宽高 */
      margin-left: -100px;
      margin-top: -100px;
    }


    /*  未知宽高进行居中  */
    #unknown {
      position: relative;
      height: 500px;
      background: orchid;
    }

    #unknown p {
      width: 200px;
      height: 200px;
      background: orangered;
      position: absolute;
      margin: auto;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
    }

    /* 图片的居中 */
    #images {
      line-height: 800px;
      text-align: center;
    }

    img {
      vertical-align: middle;
    }
  </style>
</head>

<body>
  <!--  已知宽高进行居中  -->
  <!-- <div id="known">
    <p></p>
  </div> -->

  <!-- 未知宽高进行居中 -->
  <!-- <div id="unknown">
    <p></p>
  </div> -->

  <!-- 图片的居中 -->
  <div id="images">
    <img src="../img/8.jpg" alt="">
  </div>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/qq_45279574/article/details/109097730