Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

html - Problem vertically aligning text of an element that spans two lines

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...