首页 > 解决方案 > 在另一个 div 中居中多个 div

问题描述

我想在一个 div 中水平和垂直居中 3 个 div。我不能使用 flexbox,因为后来更多的 div 和 flexbox 会影响这些新的 div,但我不知道如何垂直居中

<div class="hero">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

.hero {
  width: 100vw;
  height: 100vh; 
  text-align: center;
}

.box {
    width: 250px;
    height: 350px;
    background: red;
    margin: 50px;
    display: inline-block;
}

标签: htmlcss

解决方案


在将其撞到一半之后,仍然可以通过将其推高一半来使其居中:

.parent {
  position: relative;
}

.child {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

更新:(H优先):

html, body {
    height: 100%;
}
.hero {
    text-align: center;
    align-items: center;
    vertical-align: middle;
    justify-content: center;
    position: relative;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

.box {
    width: 250px;
    height: 350px;
    background: red;
    margin: 5px;
    top: 50%;
    position: relative;
    display: inline-block;
}

推荐阅读