如何垂直对齐具有百分比高度的div中间的文本?

问题描述:

这里是我现在有。在其他div中使用 vertical-align:middle 并将 line-height 设置为与 height 属性应该工作!唯一的是,在那些div我使用像素维度而不是百分比。任何人都可以告诉我为什么这将无法使用百分比?还将 text-size 设置为50%也应该使文本的大小为div的一半,但它真的还真的很小?这是怎么回事?

Here is what I have right now. In other divs using vertical-align:middleand setting the line-height to the same value as the height property it should work!The only thing is that in those divs I used pixel dimension and not percentages. Can anybody tell me why this wont work with percentages? also setting the text-sizeto 50% should also make text half the size of the div but it is really really small still? What is going on here?

#chooseStateAlabama {
    width: 20%;
    height: 25%;
    top: 0;
    left: 0;
    position: absolute;
    background: url(../_images/_unitedStates/_states/chooseStateAlabama.png);
    background-size: 100% 200%;
    float: left;
    color: #FFFFFF;
    font-family: Arial;
    font-style: normal;
    font-weight: bold;
    font-size: 50%;
    line-height: 25%;
    text-align: center;
    vertical-align: middle;
}


$ c> display:inline-block , height:100% vertical-align:middle 添加到文本之前或之后的单个元素或伪元素: DEMO

You can use display:inline-block , height:100% and vertical-align:middle to a single element or pseudo element aside the text (before or after): DEMO

#chooseStateAlabama:before {/* this can be an extra tag within HTML structure if pseudo used for other purpose */
    content:'';
    display:inline-block;
    height:100%;
    vertical-align:middle;
}

如果您碰巧有更多的内容或超过1行,元素来包装它,并应用于它显示和vertical-align。 DEMO2查看行为

If you happen to have more content or more than 1 line, then use an element to wrap it as well and apply to it display and vertical-align. DEMO2 to see behavior