Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem vertically aligning text of an element that spans two lines

Tags:

html

css

xhtml

I want to align some text in the middle of my element using CSS. This is my markup:

<div id="testimonial">
    <span class="quote">Some random text that spans two lines</span>
</div>

And the relevant CSS:

#testimonial {
    background: url('images/testimonial.png') no-repeat;
    width: 898px;
    height: 138px;
    margin: 0 auto;
    margin-top: 10px;
    text-align: center;
    padding: 0px 30px 0px 30px;
}

.quote {
    font-size: 32px;
    font-family: "Times New Roman", Verdanna, Arial, sans-serif;
    vertical-align: middle;
    font-style: italic;
    color: #676767;
    text-shadow: 1px 1px #e7e7e7;
}

Usually to get .quote in the vertical middle of #testimonial, I'd do:

.quote { line-height: 138px; }

But this breaks the layout because the text in .quote spans more than one line.

As you can see I've tried doing vertical-align: middle; and that doesn't work either.

Any help is appreciated. Cheers.

like image 352
Josh Avatar asked May 30 '11 19:05

Josh


1 Answers

I recently found out that vertical centering of something which has undefined dimensions goes very well with vertical-align: middle; in combination with line-height: 0;.

Check out this demonstration fiddle.

HTML:

<div id="testimonial">
    <span><span class="quote">Some random text<br />that spans two lines</span></span>
</div>

CSS:

#testimonial {
    background: #333 url('images/testimonial.png') no-repeat;
    width: 898px;
    height: 138px;
    margin: 0 auto;
    margin-top: 10px;
    text-align: center;
    padding: 0 30px 0 30px;
    line-height: 138px;
}
#testimonial>span {
    display: inline-block;
    line-height: 0;
    vertical-align: middle;
}
.quote {
    font-size: 32px;
    font-family: "Times New Roman", Verdanna, Arial, sans-serif;
    font-style: italic;
    color: #676767;
    text-shadow: 1px 1px #e7e7e7;
    line-height: 32px;
}
like image 146
NGLN Avatar answered May 22 '23 10:05

NGLN