Html h1 上的垂直对齐不起作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6802474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Vertical-align on h1 just won't work?
提问by Naatan
I'm trying to align the text in a h1
vertically to the middle, seeing as the text might wrap it needs to look nice whether it's 1 line or 2.
我试图将文本h1
垂直对齐到中间,因为文本可能会换行,无论是 1 行还是 2 行,它都需要看起来不错。
This is the css I use:
这是我使用的css:
h1 {
font-size: 12pt;
line-height: 10pt;
min-height: 30px;
vertical-align: middle;
}
The html is quite simply:
html很简单:
<h1>title</h1>
No matter what value I enter for vertical-align
, the text is always at the top of the h1
element.
无论我为 输入什么值vertical-align
,文本始终位于h1
元素的顶部。
Am I miss-understanding the vertical-align
property?
我是否误解了该vertical-align
属性?
采纳答案by NGLN
No CSS hacks needed. If I understand you correctly, then you can use this CSS:
不需要CSS hacks。如果我理解正确,那么你可以使用这个 CSS:
h1 {
font-size: 12pt;
line-height: 10px;
padding: 10px 0;
}
See demo fiddlewhich equals a minimum height of 30px;
请参阅演示小提琴,它等于 30px 的最小高度;
A note about vertical-align: that style only works in conjunction with - and is calculated with regard to - the line-height style. So setting line-height at 10px, putting text with height 12pt leaves no space to align at all. But setting line-height to 30px would result in too much space between more lines of text. This shows a trickfor vertical aligning several lines of text, but that is only needed when you have a fixed height container. In this case the container's height (the h1 element) is fluid, so you can use this simple padding solution.
关于垂直对齐的说明:该样式仅与 - 结合使用,并根据 - 行高样式进行计算。因此,将 line-height 设置为 10px,放置高度为 12pt 的文本,根本没有对齐的空间。但是将 line-height 设置为 30px 会导致更多文本行之间的空间太大。这显示了垂直对齐多行文本的技巧,但仅当您有固定高度的容器时才需要。在这种情况下,容器的高度(h1 元素)是可变的,因此您可以使用这个简单的填充解决方案。
回答by hakan
I dont know about vertical align, but if you add height property and set height and line-height properties same you get the vertical align: center effect
我不知道垂直对齐,但是如果您添加高度属性并设置高度和行高属性相同,您将获得垂直对齐:居中效果
h1
{
font-size: 12pt;
line-height: 50px;
height: 50px;
}
回答by Nathan Campos
Just add a float
property and use padding-top: 50%
for example:
只需添加一个float
属性并使用padding-top: 50%
例如:
h1 {
font-size: 12pt;
line-height: 10pt;
min-height: 30px;
position: absolute;
float: center; /* If you want it to be centered */
padding-top: 50%;
}