使用CSS进行文本的垂直和水平对齐

uni*_*zor 1 html css center alignment

我试图在div框(背景颜色)内水平和垂直对齐文本,但我无法做到.

我在网上搜索过margin: auto,text-align: center并没有做好工作.

有小费吗?

检查FIDDLE.

HTML

<div id="services"><div class="holder container clearfix">
<div class="bgtop"><span class="top">Corte cabelo + Afiar</span></div>
<div class="bgprice"><span class="price">10€</span></div>
</div></div>
Run Code Online (Sandbox Code Playgroud)

CSS

#services .holder .bgtop{
    background-color: #27ae60;
    height:50px;
    width:200px;
    z-index: 1;
}
#services .holder .bgprice{
    height:50px;
    width:90px;
    background-color: #272727;
    z-index: 1;
}
#services .holder span.top{
    color: white;
    font-style: italic;
    font-weight: bold;
    font-size: 1.000em;
    z-index: 2;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;  
    margin: auto;
    text-align: center;
}
#services .holder span.price{
    color: white;
    font-style: italic;
    font-weight: bold;
    font-size: 1.500em;
    z-index: 2;
    text-align: center;
}
Run Code Online (Sandbox Code Playgroud)

Jos*_*ier 6

这是用于垂直/水平居中的常用方法.

这里的基本例子

div {
    background: red;
    width:100px;
    height: 100px;
    display:table;
}
div > span {
    display:table-cell;
    vertical-align:middle;
    text-align:center;
}
Run Code Online (Sandbox Code Playgroud)

基本上,父元素的显示更改为table.添加一个子元素,在本例中是一个span包装文本的元素.本span应具有的属性display:table-cell/ vertical-align:middle垂直居中.然后text-align:center只是水平居中.

这是一个使用你的样式的例子.