这似乎是我发现这个问题的最佳解决方案,只要你的浏览器支持::before伪元素:CSS-Tricks:以未知为中心。它不需要任何额外的标记,似乎工作得非常好。我无法使用该display: table方法,因为table元素不遵守该max-height属性。.block {
height: 300px;
text-align: center;
background: #c0c0c0;
border: #a0a0a0 solid 1px;
margin: 20px;}.block::before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -0.25em; /* Adjusts for spacing */
/* For visualization
background: #808080; width: 5px;
*/}.centered {
display: inline-block;
vertical-align: middle;
width: 300px;
padding: 10px 15px;
border: #a0a0a0 solid 1px;
background: #f5f5f5;}<div class="block">
<div class="centered">
<h1>Some text</h1>
<p>But he stole up to us again, and suddenly clapping his hand on my
shoulder, said—"Did ye see anything looking like men going
towards that ship a while ago?"</p>
</div></div>
这是我需要多次执行的操作,一致的解决方案仍然需要添加一些非语义标记和一些特定于浏览器的黑客。当我们获得css 3的浏览器支持时,你将获得垂直居中而不会犯罪。基本上它涉及添加一个额外的元素,并在IE和支持position:table\table-cell非表元素的浏览器中应用不同的样式。<div class="valign-outer">
<div class="valign-middle">
<div class="valign-inner">
Excuse me. What did you sleep in your clothes again last night. Really. You're gonna be in the car with her. Hey, not too early I sleep in on Saturday. Oh, McFly, your shoe's untied. Don't be so gullible, McFly. You got the place fixed up nice, McFly. I have you're car towed all the way to your house and all you've got for me is light beer. What are you looking at, butthead. Say hi to your mom for me. </div>
</div></div><style>
/* Non-structural styling */
.valign-outer { height: 400px; border: 1px solid red; }
.valign-inner { border: 1px solid blue; }</style><!--[if lte IE 7]>
<style>
/* For IE7 and earlier */
.valign-outer { position: relative; overflow: hidden; }
.valign-middle { position: absolute; top: 50%; }
.valign-inner { position: relative; top: -50% }
</style>
<![endif]--><!--[if gt IE 7]> --><style>
/* For other browsers */
.valign-outer { position: static; display: table; overflow: hidden; }
.valign-middle { position: static; display: table-cell; vertical-align: middle; width: 100%; }</style>