问题
I am trying to vertically center some text in a <span>
element, in relation to a much larger <span>
that is a sibling of the first one. Both are children of a containing parent <div>
element.
HTML:
<div>
<span class="previewLabel">Preview:</span>
<span class="previewText">The quick brown fox jumps over the lazy dog.</span>
</div>
CSS:
.previewLabel {
display: inline-block;
line-height: 100%;
vertical-align: middle;
}
.previewText {
font-family: Verdana, Geneva, sans-serif;
font-size: 64px;
font-style: italic;
font-weight: bold;
}
JSFiddle: http://jsfiddle.net/5chXG/
As you can see, I already tried the vertical-align
trick (with the line-height
defined) that is described in this Q&A ("Text vertical align in a div") but it doesn't seem to work. I think the difference is that I can't use a static line-height
value.
I can't use a px
value for the line-height
property because the .previewText
span can change sizes dynamically. In the real code, there are controls on the page to change the font properties and JavaScript will adjust the CSS of the .previewText
while you change things.
My Question:
How can make the "Preview:" text (.previewLabel
) <span>
be vertically aligned in the middle of the parent <div>
element?
Edit / Clarification
I would like ALL of the text to behave as a single line of text normally would.
- Wrapping should cause the big text to flow under the smaller text.
- The smaller text should only be vertically aligned within the height of a single line of larger text, not multiple lines
Here is a visualization of what I am trying to achieve:

回答1:
Adding vertical-align:middle
to both .previewLabel
and .previewText
will work just fine.
And here is a fiddle for proof: http://jsfiddle.net/pavloschris/5chXG/4/
回答2:
If you want the left one-line text to align to the first line of multi-line text on the right, you need to use vertical-align: baseline
instead of vertical-align: middle
along with display: table-cell
. .previewLabel
doesn't need a set line-height.
DEMO
.previewLabel {
vertical-align: baseline;
}
span {
display:table-cell;
}
来源:https://stackoverflow.com/questions/21888515/vertically-center-span-text-which-is-beside-a-much-larger-span-both-inside