You can try this basic approach:
(您可以尝试以下基本方法:)
div { height: 90px; line-height: 90px; text-align: center; border: 2px dashed #f69c55; }
<div> Hello World! </div>
It only works for a single line of text though, because we set the line's height to the same height as the containing box element.
(但是,它仅适用于一行文本,因为我们将行的高度设置为与包含框元素相同的高度。)
A more versatile approach (更通用的方法)
This is another way to align text vertically.
(这是垂直对齐文本的另一种方法。)
This solution will work for a single line and multiple lines of text, but it still requires a fixed height container: (此解决方案适用于一行和多行文本,但仍需要一个固定高度的容器:)
div { height: 200px; line-height: 200px; text-align: center; border: 2px dashed #f69c55; } span { display: inline-block; vertical-align: middle; line-height: normal; }
<div> <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Haec et tu ita posuisti, et verba vestra sunt. Non enim iam stirpis bonum quaeret, sed animalis. </span> </div>
The CSS just sizes the <div>
, vertically center aligns the <span>
by setting the <div>
's line-height equal to its height, and makes the <span>
an inline-block with vertical-align: middle
.
(CSS仅调整<div>
大小,通过将<div>
的line-height设置为其高度,使居中的<span>
垂直对齐,并使<span>
成为具有vertical-align: middle
的内联块。)
Then it sets the line-height back to normal for the <span>
, so its contents will flow naturally inside the block. (然后将<span>
的行高设置回正常,因此其内容将自然地在块内流动。)
Simulating table display (模拟表显示)
And here is another option, which may not work on older browsers that don't support display: table
and display: table-cell
(basically just Internet Explorer 7).
(这是另一个选项,在不支持display: table
和display: table-cell
旧版浏览器中可能无法使用(基本上只是Internet Explorer 7)。)
Using CSS we simulate table behavior (since tables support vertical alignment), and the HTML is the same as the second example: (使用CSS我们模拟表的行为(因为表支持垂直对齐),并且HTML与第二个示例相同:)
div { display: table; height: 100px; width: 100%; text-align: center; border: 2px dashed #f69c55; } span { display: table-cell; vertical-align: middle; }
<div> <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span> </div>
Using absolute positioning (使用绝对定位)
This technique uses an absolutely positioned element setting top, bottom, left and right to 0. It is described in more detail in an article in Smashing Magazine, Absolute Horizontal And Vertical Centering In CSS .
(此技术使用绝对定位的元素将top,bottom,left和right设置为0。在Smashing Magazine的CSS中的绝对水平和垂直居中中对此进行了详细介绍。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…