两个div内的中心元素垂直

时间:2017-06-22 13:33:42

标签: css

如何将这四个按钮垂直和水平放在他们自己的div中?

更新:请不要使用Flexbox。我没那么奢侈。

#outer {
  width: 400px;
  height: 200px;
  background-color: black;
  display: table-cell;
}

#innerOne {
  width: 400px;
  height: 100px;
  background-color: red;
  vertical-align: middle;
}

#innerOne {
  width: 400px;
  height: 100px;
  background-color: blue;
  vertical-align: middle;
}
<div id="outer">
  <div id="innerOne">
    <button>One</button>
    <button>Two</button>
  </div>
  <div id="innerTwo">
    <button>Three</button>
    <button>Four</button>
  </div>
</div>

我希望“one”,“two”在蓝色div内垂直和水平居中。黑色div中的“三”和“四”相同。

我通过将显示设置为table和table-cell而没有达到我想要的效果,尝试了很多不同的选项。

2 个答案:

答案 0 :(得分:1)

由于按钮是内联块,您可以使用伪元素垂直居中。伪元素具有容器的高度(.inner),并且垂直对齐,并且所有高度较小的内联块将以其为中心。 要将它们水平居中,请在容器(text-align: center)上设置.inner

&#13;
&#13;
#outer {
  width: 400px;
  height: 200px;
  background-color: black;
}

.inner {
  width: 400px;
  height: 100px;
  text-align: center;
}

.inner::before {
  display: inline-block;
  height: 100%;
  content: '';
  vertical-align: middle;
}

#innerOne {
  background-color: red;
}

#innerTwo {
  background-color: blue;
}
&#13;
<div id="outer">
  <div id="innerOne" class="inner">
    <button>One</button>
    <button>Two</button>
  </div>
  <div id="innerTwo" class="inner">
    <button>Three</button>
    <button>Four</button>
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

对于一行,您可以使用line-height等于内联内容框中的heightvertical align

水平部分

text-align

&#13;
&#13;
#outer {
  width: 400px;
  height: 200px;
  background-color: black;
  /*display: table-cell;useless here i believe*/
  text-align:center;
}


#innerOne,
#innerTwo {
  width: 400px;
  height: 100px;
  line-height:100px;
  background-color: blue;
}
#innerOne {
  background-color: red;
}
&#13;
<div id="outer">
  <div id="innerOne">
    <button>One</button>
    <button>Two</button>
  </div>
  <div id="innerTwo">
    <button>Three</button>
    <button>Four</button>
  </div>
</div>
&#13;
&#13;
&#13;