如何垂直对齐2个不同大小的文本?

我知道要将文本垂直对齐到块的中间,需要将行高设置为块的相同高度。

但是,如果我有一个句子中间有一个单词,那就是 2em。如果整个句子的行高与包含块相同,那么较大的文本是垂直对齐的,但较小的文本与较大的文本在相同的基线上。

我如何设置它,使两个大小的文本垂直对齐,使较大的文本将在基线低于较小的文本?

101732 次浏览

You technically can't, however, if you have fixed text sizes you could use positioning (relative) to move the larger text down and set the line-height to the smaller text (I'm presuming this larger text is marked up as such so you can use that as a CSS selector)

Try vertical-align:middle; on inline containers?

EDIT : it works but all your text must be in an inline container, like this :

    <div style="height:100px; line-height:100px; background:#EEE;">
<span style="vertical-align:middle;">test</span>
<span style="font-size:2em; vertical-align:middle;">test</span>
</div>

The functionality you are seeing is correct because the default for "vertical-align" is baseline. It appears that you want vertical-align:top. There are other options. See here at W3Schools.

Edit W3Schools has not cleaned up their act and still, appear, to be a shoddy (at best) source of information. I now use sitepoint. Scroll to the bottom of the sitepoint front page to access their reference sections.

An option is to use a table there the different sized texts are in their own cells and use align:middle on each cell.

Its not pretty and does not work for all occasions, but it is simple and works with any text size.

the two set of text must have the same fixed line-height and the vertical-align set

 span{
vertical-align: bottom;
line-height: 50px;
}

This works

header > span {
margin: 0px 12px 0px 12px;
vertical-align:middle;
}
.responsive-title{
font-size: 12vmin;
line-height: 1em;
}
.responsive-subtitle{
font-size: 6vmin;
line-height: 2em;
}
<header>
<span class="responsive-title">Foo</span>
<span class="responsive-subtitle">Bar</span>
</header>

You can use percentage sizes to reapply the parent's line-height

.big {
font-size: 200%;
line-height: 25%;
display: inline-block;
vertical-align: middle;
}
Utque aegrum corpus <span class="big">etiam</span> levibus solet offensis 

Easy way - use flex:

<div>
abcde
&nbsp;&nbsp;
<span>efghai</span>
</div>


<style>
div {
padding: 20px;
background-color: orange;
display: flex;
align-items: center; }


span {
font-size: 1.5em; }
</style>