用vertical-align属性排列内联图片

October 5th, 2008

最近,我收到了如下问题:

你如何将一张图片垂直的定位在一段文本中?

答案

让我们应用一个例子-包含一行文本和一张小图片(如下的蓝色盒子所显示)的段落。

Sample of text with inline image

接下来,我们需要观察6种主要的能够被用来垂直排列的行。

文本行

1. 头行 - 所有内容之上的头行

Sample text showing top line in red

2. 文本头行 - 包括所有重音符号文本的头行

Sample text showing text-top in red

注意: 头行和 “文本” 头行看起来是一样的。然而,有时候头行(下面红色部分)更高一些,其中的内容也比文本头行(下面绿色部分)更高一些。一个例子就是一张图片在这行文本之中:

Sample text showing top and text-top

3. 中线 - x-height(字母x的高度)的垂直中央

Sample text showing middle line in red

4. 基线 - 所有字母所在的一条假想的线

Sample text showing baseline in red

5.文本底线 - 包括下行字符(诸如 “j”, “y”, “g” 等)的所有文本的底部。

Sample text showing text-bottom in red

6. 底线 - 所有内容的底线

Sample text showing bottom line in red

图片的默认垂直排列

默认的,图片的底部将会和段落的基线对齐 - 除非给图片应用margin-bottom。那么,图片的底部的margin-bottom将会与段落的基线对齐。在下面的例子中,图片应用了“margin-bottom: 5px”,这使得图片的底部比基线高出了5px。

Sample text showing margin pushing image up from baseline

使用CSS来改变垂直排列

你可以使用CSS vertical-align 属性来改变图片相对于四周文本的竖直位置。

可以使用的属性包括:top, text-top, middle, baseline, text-bottom, bottom, sub, super, percentage and length。

头部

图片的顶端将会与头行对齐。

img.class-name { vertical-align: top; }

Sample text showing image aligned to top

文本头部

图片的头部将会与文本头部对齐。

img.class-name { vertical-align: text-top; }

Sample text showing image aligned to text-top

中部

图片的垂直中点将会与段落基线加上段落中x高度的一半对齐。

img.class-name { vertical-align: middle; }

Sample text showing image aligned to middle

基线

尽管图片会使用基线作为默认的行为来进行垂直排列,你仍然可以使用CSS来进行详细说明。

img.class-name { vertical-align: baseline; }

Sample text showing image aligned to baseline

文本底部

图片的底部将会与文本底线对齐。

img.class-name { vertical-align: text-bottom; }

Sample text showing image aligned to text-bottom

底部

图片的底部将会与底线对齐。

img.class-name { vertical-align: bottom; }

Sample text showing image aligned to bottom

下标

图片的底部将会与下标内容的基线位置对齐(不管是否有任何的下标内容存在)。

img.class-name { vertical-align: sub; }

Sample text showing image aligned to sub

上标

图片的底部将会与上标内容的基线位置对齐(不管是否有任何的上标内容存在)。

img.class-name { vertical-align: super; }

Sample text showing image aligned to super

百分比

通过设定详细值将会增加(正值)或者减少(负值)图片与基线位置的距离。‘0%’ 与 ‘baseline’表示相同的意思。各种浏览器在定位基于百分比的垂直排列上差别不大。

img.class-name { vertical-align: 30% }

Sample text showing image aligned with positive percentage

img.class-name { vertical-align: -30% }

Sample text showing image aligned with negative percentage

长度

通过设定详细值将会增加(正值)或者减少(负值)图片与基线位置的距离。 ‘0%’ 与 ‘baseline’表示相同的意思。

img.class-name { vertical-align: 2px }

Sample text showing image aligned with positive pixels

img.class-name { vertical-align: -2px }

Sample text showing image aligned with negative pixels

那么,你现在感受如何呢… 你发现 vertical-align 很有用处吗?你会用它排列内容中的图片吗?

Translation