前言导读
利用 CSS 来实现对象的垂直居中有许多不同的方法,比较难的是选择那个正确的方法。使用 CSS 实现水平居中很容易,但要实现垂直居中并不容易。而且有些方法在一些浏览器中无效。下面我们看一下使对象垂直集中的几种不同方法,以及它们各自的优缺点。
表格布局
<html>
<head>
<title>css居中属性</title>
</head>
<style>
#wrapper {
display: table;
}
#likeImg {
display: inline-block;
vertical-align: center;
}
</style>
<body>
<div id="wrapper">
<div id="likeImg">
<div class="content">Content goes here</div>
</div>
</div>
</body>
</html>
content 可以动态改变高度(不需在 CSS 中定义)。当 wrapper 里没有足够空间时, content 不会被截断.
Internet Explorer(甚至 IE8 beta)中无效,许多嵌套标签(其实没那么糟糕,另一个专题).
假借图片法
<html>
<head>
<title>css居中属性</title>
</head>
<style>
#wrapper {
display: table;
}
#likeImg {
display: inline-block;
vertical-align: center;
}
</style>
<body>
<div id="wrapper">
<div id="likeImg">
<div class="content">Content goes here</div>
</div>
</div>
</body>
</html>
在各种浏览器中兼容性都非常好,ie6和7中有间距问题
很容易影响其他的布局,导致网页布局全部瘫痪
绝对定位法
<html>
<head>
<title>css居中属性</title>
</head>
<style>
#content {
position: absolute;
top: 50%;
height: 240px;
margin-top: -120px; /* 盒子本身高度的一半 */
}
</style>
<body>
<div class="box">
<div id="content"> Content goes here</div>
</div>
</body>
</html>
适用于所有浏览器 不需要嵌套标签
没有足够空间时,content 会消失(类似div 在 body 内,当用户缩小浏览器窗口,滚动条不出现的情况)
追加元素
<html>
<head>
<title>css居中属性</title>
</head>
<style>
#floater {
float: left;
height: 50%;
margin-bottom: -120px;
}
#content {
clear: both;
height: 240px;
position: relative;
}
</style>
<body>
<div id="box">
<div id="content">Content here</div>
<div id="floater">
</div>
</body>
</html>
适用于所有浏览器 没有足够空间时(例如:窗口缩小) content 不会被截断,滚动条出现
唯一我能想到的就是需要额外的空元素了,可能对于某些强迫症患者来说是不愿意的(这个方法的应用应该也很广)
设置宽度
<html>
<head>
<title>css居中属性</title>
</head>
<style>
#content {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
height: 240px;
width: 70%;
}
</style>
<body>
<div id="box">
<div id="content"> Content here</div>
</div>
</body>
</html>
简单粗暴,代码简单,其实设计者当初也根本没想到也能这样用,但是聪明的大家硬是凿出了一条简单的路。
IE(IE8 beta)中无效 无足够空间时,content 被截断,但是不会有滚动条出现
如何让文本水平垂直居中
<html>
<head>
<title>css居中属性</title>
</head>
<style>
.content{
padding: 0px;
width:500px;
height:200px;
text-align:center;
background-color:#F69;
display: table-cell;
vertical-align:middle
}
</style>
<body>
<div class="content">
文本居中
</div>
</body>
</html>