如何垂直居中多个元素?

How to Vertically Center Multiple Elements?

我浏览了整个网站(以及互联网的其余部分),唯一真正提到垂直居中两个或更多的问题是 this one, but the only answer there seems to just be an entire code review. In the process of learning CSS, I still cannot reliably position things centrally in the order I want them. Horizontally centering is often just as difficult, although I've managed in the minimal code example below. I know of howtocenterincss.com 但这只能让我垂直对齐一件事。

在下面的代码示例中,我希望两个按钮共同位于 div 的中心,一个放在另一个上方,中间留有空白。我已经成功完成了一半,但不太清楚如何在 div.

中垂直对齐它们

#buttonContainer {
  display: inline-block;
  border: solid 3px black;
  width: 400px;
  height: 400px;
}

.button {
  display: block;
  margin: auto;
}
<div id="buttonContainer">
  <button id="b1" class="button">Button 1</button>
  <button id="b2" class="button">Button 2</button>
</div>

inline-flex 支持 IE10+

flex-direction 仅支持 IE11

align-items 仅支持 IE11

所以,我不想使用这个属性,我使用这种方式:

.center {
    position: absolute;
    top: 50%;
    left: 50%;
    -ms-transform: translate(-50%,-50%);
    transform: translate(-50%,-50%);
    display: inline-block;
}

#buttonContainer {
    display: inline-block;
    position: relative;
    border: solid 3px black;
    width: 400px;
    height: 400px;
}

.button {
    display: block;
    margin:2px;
}

.center {
    position: absolute;
    top: 50%;
    left: 50%;
    -ms-transform: translate(-50%,-50%);
    transform: translate(-50%,-50%);
    display: inline-block;
}
<div id="buttonContainer">
    <div class="center">
        <button id="b1" class="button">Button 1</button>
        <button id="b2" class="button">Button 2</button>
    </div>
</div>

我通常更喜欢使用 flexbox:

#buttonContainer {
  display: flex;
  flex-direction: column;
  justify-content: center;
  border: solid 3px black;
  width: 400px;
  height: 400px;
}

.button {
  display: block;
}
<div id="buttonContainer">
  <button id="b1" class="button">Button 1</button>
  <button id="b2" class="button">Button 2</button>
</div>

在您不想重叠的地方应用绝对定位不是一个好主意。您可以使用 flexbox 来实现所需的布局。演示:

#buttonContainer {
  /* make element inline flex-container */
  /* this will make its children flex-items */
  display: inline-flex;
  /* align-items items in column */
  flex-direction: column;
  /* center items horizontally */
  align-items: center;
  /* center items vertically */
  justify-content: center;
  
  border: solid 3px black;
  width: 400px;
  height: 400px;
}
<div id="buttonContainer">
  <button id="b1" class="button">Button 1</button>
  <button id="b2" class="button">Button 2</button>
</div>