这是一个避免使用<table> 标签的解决方案。
它适用于 Internet Explorer 8 和 9、Chrome、Firefox 和 Safari(但不适用于 IE7,但我上次检查它们的全球市场份额约为 2%)。
首先,摆脱尝试在段落标签中垂直对齐文本的想法 - 而是考虑在容器中对齐段落。
使用标记...
<div class="container">
<p>The text that you'd wish to have vertically aligned in the middle of the
container...which might be like an article column, or whatever</p>
</div>
和 CSS
.container{
border: 1px solid red; /*to see the example*/
display: table-cell;
height: /* insert whatever height you want*/;
vertical-align: middle;
}
这会将段落垂直对齐到容器元素的垂直中心。
现在一个非常有趣的解决方案是,当您拥有一个充满内容的父容器时,您希望所有子容器并排并排并与中间完全垂直对齐。
当然,如果您希望父容器具有特定大小,则使用此版本:
标记:
<div class="containerTwo">
<p>here's some text and stuffs, make this whatever the heck
you want it to be</p>
<p>these can be any height and, really any element, the magic
is in the display property of the elements so this still
looks pretty semantic</p>
<p>more stuff and this could be like an image or something</p>
</div>
CSS:
.containerTwo{
border: 1px solid green; /* for sake of the example */
display: table-cell;
height: /* what you want it to be */;
vertical-align: middle;
}
.containerTwo p{
border: 1px solid blue; /* for sake of example */
display: inline-block;
width: 30%; /* all of the child elems shouldn't go over 100% */
vertical-align: middle;
}
这将生成一个父元素,您可以选择任意高度,并且所有子元素都在中间完美对齐。当您有一堆不同的高度元素都想在中间对齐并且您不想为父元素指定高度时,甚至不需要display: table-cell 的更酷的解决方案是可能的但只是希望它伸展到最大子元素的高度:(哦,这在 IE7 中有效)
标记:
<div class="containerThree">
<p>this is more text that you might want to have
vertically aligned in the middle with the others</p>
<p>so here's a sibling paragraph you might want to
have aligned next to the other.</p>
<div title="a really big element!"></div>
<p>like the last one, the width can't add up to more
than 100% of the parent element, otherwise they just
wrap. But atleast no table-cell!</p>
</div>
CSS:
.containerThree{
border: 1px solid purple; /* for the example */
/* and that's it!!! */
}
.containerThree p, .containerThree div{
border: 1px solid blue;
width: 20%; /* can't add beyond total width of parent */
display: inline-block;
*display: inline; /* ie7 hack */
zoom: 1; /* ie7 hack */
vertical-align: middle;
}
.containerThree div{ /* to simulate a big element */
height: 400px;
}
对于这个,一切都将相互垂直对齐。
这是一个关于 js fiddle 的示例,供您查看:
http://jsfiddle.net/NJqMp/1/