方法一
<div class="table" style="height: 200px;"><div class="table-cell">content</div></div>.table {display:table;}.table-cell {display:table-cell; vertical-align:middle;}
优点:content 可以动态改变高度,如果你不需要支持IE7浏览器,这个应该是首选方案,也是W3C推荐的方案。
缺点:IE7和IE8 beta不支持。
方法二
<div class="content">Content</div>#content { position:absolute; top:50%; height:240px; margin-top:-120px; /* negative half of the height */ overflow: auto;}
优点:适用于所有浏览器。
缺点:内容区域高度固定,如果不用overflow:hidden或overflow:auto,内容显示就会超出内容区域,看起来就不是居中了。
而使用overflow:hidden,超出的内容就会消失;使用overflow:auto则会出现滚动条。
方法三 – 不推荐使用
这个方法利用的是margin:auto的计算方法,给内容区域div#content设置一个固定高度,并且设置position:absolute;top:0; bottom:0;。因为它有固定高度,其实并不能使上下都间距为 0,,因此 margin:auto; 会使它垂直居中。
<divid="content">Content </div>#content{ position:absolute; top:0; bottom:0; margin:auto; height:240px;}
优点:明显不如第一种方法,一般不用。
缺点:IE7和IE8 beta中无效;因为内容区域高度固定,和第二种方法有相同的问题。
方法四
这个方法只能将单行文本置中。只需要简单地把 line-height 设置为内容容器的height 值就可以使文本居中了。
<divid="content">Content </div>#content{height:100px; line-height:100px;}
优点:适用于所有浏览器;在文本不换行的小元素上非常有用,例如使按钮文本或者单行文本居中。
缺点:只对文本有效(块级元素无效);多行时因为line-height太高,行距会非常大;
往往教导我们大家要好好学习天天向上,