Html CSS - 垂直对齐 DIV 内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1881245/
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
CSS - Vertically Align DIV content
提问by user208662
I am trying to vertically center some content via CSS. For the life of me, I cannot figure out the cause. Can someone tell me why the word "test" in the following HTML is always top-aligned no matter what I do?
我试图通过 CSS 垂直居中一些内容。对于我的生活,我无法弄清楚原因。有人能告诉我为什么无论我做什么,下面 HTML 中的“测试”这个词总是顶部对齐的吗?
<html>
<head>
<title>test</title>
</head>
<body>
<table border='0' cellpadding='0' cellspacing='0'>
<tr><td style='height:200px; width:300px; background-color:silver;'>
<div style='height:100%; width:100%; background-color:gray; text-align:center;'>
<div style='vertical-align:middle;'>test</div>
</div>
</td></tr>
</table>
</body>
</html>
Thank you very much for your help!
非常感谢您的帮助!
回答by Francisco Aquino
A quick way to vertical align, like in your case, is to match the line-height with the height.
垂直对齐的一种快速方法,就像您的情况一样,是将行高与高度相匹配。
<html>
<head>
<title>test</title>
</head>
<body>
<table border='0' cellpadding='0' cellspacing='0'>
<tr><td style='height:200px; line-height: 200px; width:300px; background-color:silver;'>
<div>
<div style="text-align: center">test</div>
</div>
</td></tr>
</table>
</body>
</html>
回答by dxh
Because vertical-align
is only a CSS substitute to the valign
attribute in TD
, and therefore only works on display: table-cell
elements (and no, the proper solution is not to change the displaymode of your DIV
)
因为vertical-align
只是 中valign
属性的 CSS 替代品TD
,因此仅适用于display: table-cell
元素(不,正确的解决方案是不更改 中的显示模式DIV
)
If you can set a fixed height to the div, you should be able to align it vertically with margin: auto 0
如果您可以为 div 设置固定高度,则应该能够将其垂直对齐 margin: auto 0
回答by user1040259
回答by inkedmn
Try adding valign="middle"
to your td
tag, like:
尝试添加valign="middle"
到您的td
标签中,例如:
<td valign="middle" style='height:200px; width:300px; background-color:silver;'>
回答by rui
Try setting style='vertical-align:middle;' in the parent element. Right now you are indeed telling the inner div to align the text to the middle, however you're not telling it to stretch and occupy the whole page. Basically you're ending up with a div element that's as small as the text.
尝试设置 style='vertical-align:middle;' 在父元素中。现在您确实是在告诉内部 div 将文本与中间对齐,但是您并没有告诉它拉伸并占据整个页面。基本上,您最终会得到一个与文本一样小的 div 元素。
You can use Firebug plugin in Firefox to debug this kind of CSS issue!
您可以在 Firefox 中使用 Firebug 插件来调试此类 CSS 问题!
回答by Saif Bechan
try using line-height:100px
尝试使用 line-height:100px