简体   繁体   English

垂直对齐不会使文本居中

[英]vertical-align doesn't center the text

I have the following css: 我有以下CSS:

#header-notification 
{
    color: #7B6F60;
    font-size: 13px;
    font-weight: bold;
    float: left;
    text-align: center;
    vertical-align: middle;

    height: 20px;
    width: 20px;
    background-color: #E5E5E5;
}

and declared the label as: 并将标签声明为:

  <label id="header-notification"></label>

However doing so gives me the following: 但是这样做给我以下几点:

在此处输入图片说明

As you can see the text here is not vertically centered. 如您所见,此处的文本未垂直居中。 What am I doing wrong? 我究竟做错了什么?

As you are using a single character to align it vertically, you can use line-height property here to vertically align in the middle of the element 当您使用单个字符垂直对齐时,可以在此处使用line-height属性在元素中间垂直对齐

Demo 演示版

#header-notification {
    color: #7B6F60;
    font-size: 13px;
    font-weight: bold;
    float: left;
    text-align: center;
    vertical-align: middle;
    height: 20px;
    width: 20px;
    background-color: #E5E5E5;
    line-height: 20px;
}

For making vertical-align: middle; 为了使vertical-align: middle; work, you need to use display: table-cell; 工作时,需要使用display: table-cell; so that it will align middle vertically.. but you won't need that here as I specified that you are trying to align a single character. 这样它就可以垂直居中对齐。.但是您不需要这里,因为我指定要对齐一个字符。 display: table-cell; method is generally used when you want to align an entire paragraph or an image vertically inside an element. 当要在元素内垂直对齐整个段落或图像时,通常使用此方法。

Give this a spin: http://jsfiddle.net/jplahn/7zwUc/ 试一下: http : //jsfiddle.net/jplahn/7zwUc/

You need to place it inside a parent div. 您需要将其放在父div内。 (If you want to use vertical-align on it. Obviously there's other ways to do it). (如果要在其上使用垂直对齐。显然,还有其他方法可以做到)。

HTML: HTML:

<div id="header-notification"> 
    <label id="number">0</label>
<div>

CSS: CSS:

#header-notification 
{
    color: #7B6F60;
    font-size: 13px;
    font-weight: bold;
    float: left;
    text-align: center;

    height: 20px;
    width: 20px;
    background-color: #E5E5E5;
}

#number {
    vertical-align: middle;
}

Try to add display: table-cell for element: 尝试添加display: table-cell作为元素:

#header-notification 
{
    display: table-cell;
    color: #7B6F60;
    font-size: 13px;
    font-weight: bold;
    float: left;
    text-align: center;
    vertical-align: middle;   
    height: 20px;
    width: 20px;
    background-color: #E5E5E5;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM