skyisred
skyisred

Reputation: 7105

How to vertically align text withing its line? (vertical-align is not working)

Here is the example of what I'm talking about, you need to zoom-in to see the problem http://jsfiddle.net/54NEa/

<div id="top">SomeText</div>
<div id="middle">SomeText</div>
<div id="bottom">SomeText</div>

div{
    display: inline-block;
    background-color: red;
    font-family: Lucida Sans Unicode,Verdana,Arial,Helvetica,sans-serif;
    font-size: 10px;
    line-height: 10px;
}
div.top {vertical-align:top;}
div.middle {vertical-align:middle;}
div.bottom {vertical-align:bottom}

the line is 10px, but text doesn't fill it completely, it has extra padding - in FF the padding is below and in Chrome its above, regardless of vertical-align property. This varies somewhat with font, but it never really fills its line-height completely, it "wiggles". Any ideas how to fix that font in one position relative to its line regardless of browsers? Im making a small css button and I need to make sure my line is exactly 10px in height and the text is also precisely 10px in height, so it always look the same.

Upvotes: 0

Views: 324

Answers (3)

Tom Pietrosanti
Tom Pietrosanti

Reputation: 4294

vertical-align only applies to inline elements. Try using a span instead of a div, or set display:inline on your divs.

EDIT

You also need to set the font-size and line-height of the container. In this case, I used the body. I also changed the display to inline, since you don't seem to need inline-block, and used unitless line-height

http://jsfiddle.net/78fxj/

Upvotes: 0

raam86
raam86

Reputation: 6871

You must adjust line height to fit the element.

HTML:

    <div id="top"><span>SomeText</span></div>

div{
    height:30px;
    display: inline-block;
    background-color: red;
    font: 10px Lucida Sans Unicode,Verdana,Arial,Helvetica,sans-serif;
}

span{
    line-height:30px;
}

Here's a fiddle: http://jsfiddle.net/54NEa/1/

Upvotes: 1

Jeremy Foster
Jeremy Foster

Reputation: 4773

You can also set the div's display to table-cell. It's a pretty good solution, but sometimes it has other implications.

<div id="top">SomeText</div>
<div id="middle">SomeText</div>
<div id="bottom">SomeText</div>

div{
    display: **table-cell**;
    background-color: red;
    font: 10px/10px Lucida Sans Unicode,Verdana,Arial,Helvetica,sans-serif;
}
div.top {vertical-align:top;}
div.middle {vertical-align:middle;}
div.bottom {vertical-align:bottom}

Upvotes: 0

Related Questions