【问题标题】:Center elements inside two div vertically [duplicate]垂直居中两个div内的元素[重复]
【发布时间】:2017-11-25 19:47:02
【问题描述】:

如何让这四个按钮在各自的 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>

我希望“一”、“二”在蓝色 div 中垂直和水平居中。黑色 div 中的“三”和“四”也是如此。

我尝试了许多不同的选项,将它们的显示设置为表格和表格单元格,但没有达到我想要的效果。

【问题讨论】:

    标签: css


    【解决方案1】:

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

    #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;
    }
    <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>

    【讨论】:

      【解决方案2】:

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

      text-align 用于水平部分

      #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;
      }
      <div id="outer">
        <div id="innerOne">
          <button>One</button>
          <button>Two</button>
        </div>
        <div id="innerTwo">
          <button>Three</button>
          <button>Four</button>
        </div>
      </div>

      【讨论】:

        猜你喜欢
        • 2012-08-12
        • 2014-05-10
        • 1970-01-01
        • 1970-01-01
        • 2019-12-30
        • 1970-01-01
        • 2017-10-10
        • 2018-09-24
        • 2017-09-25
        相关资源
        最近更新 更多