欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

三种简单方法让你轻松实现div元素的垂直居中布局

最编程 2024-08-08 19:14:01
...

 使用 Flexbox 布局实现 div 垂直居中


<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<style>
  .father {
    width: 200px;
    height: 200px;
    border: 1px solid red;
    display: flex;
    align-items: center;
    /* 垂直居中 */
    justify-content: center;
    /* 水平居中 */
  }

  .child {
    width: 100px;
    height: 100px;
    border: 1px solid blue;
  }
</style>

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

</html>

 

使用 position 属性和 transform 属性实现垂直居中:

.father {
  width: 200px;
  height: 200px;
  border: 1px solid red;
  position: relative;
}

.child {
  width: 100px;
  height: 100px;
  border: 1px solid blue;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

使用 position 和 margin:auto 实现

.father {
  position: relative;
  width: 200px;
  height: 200px;
  border: 1px solid red;
}

.child {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  width: 100px;
  height: 100px;
  border: 1px solid blue;
}