2017-06-22 24 views
2

如何将这四个按钮垂直和水平居中放置在自己的div内?两个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>

我想 “一”, “二” 蓝格内的垂直和水平居中。黑色格中的“三”和“四”相同。

我已经尝试了很多不同的选项,通过将它们的显示设置为表格和表格单元而没有我想要的效果。

回答

0

为单行线,你可以在中心的在线内容使用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>

1

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

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