Css实现居中的方法
1.水平居中
text-alian:center;
2.垂直居中
1)这个方法让一些
显示成table,然后我们就可以利用table的vertical-align属性了(vertical-align作用在其他一些元素上会表现得非常不一样)。
Html代码
<div id="wrapper">
<div id="cell">
<div class="content">Content goes here</div>
</div>
</div>
Css代码
#wrapper {
display: table;
}
#cell {
display: table-cell;
vertical-align: middle;
}
优点:
1、内容可以动态地改变高度(不用在CSS里定义)。
2、空间不够的话内容不会被截断。
缺点:
1、不支持IE(即使是IE8 beta)。
2、多余的标签(没那么糟,看你自己怎么认为)。
2) 这个方法会用到一个top设为50%、margin-top设为内容高度的一半、绝对定位的div。这意味着它必须有一个固定的高度,这是在CSS里定义的。
因为它的高度固定,你可能想要给它设置overflow:auto;,这样如果内容太多的话就不会溢出而是会出现滚动条了。
Html代码
<div id="content">Content goes here</div>
Css代码
#content {
position: absolute;
top: 50%;
height: 240px;
margin-top: -120px; /* negative half of the height */
}
优点:
1、支持所有的浏览器。
2、不需要额外的标签。
缺点:
1、如果空间不够的话,内容就会消失(例如当div在body里面而用户缩小浏览器时,就不会出现滚动条)。
3)在这个方法中,我们会在内容元素上方插入一个div,这个div会被设置成height:50%;margin-bottom:-contentheight/2,然后内容元素会因为清理浮动而居中了。
Html代码
<div id="floater"></div>
<div id="content">Content here</div>
Css代码
#floater {
float: left;
height: 50%;
margin-bottom: -120px;
}
#content {
clear: both;
height: 240px;
position: relative;
}
优点:
1、支持所有的浏览器。
2、如果空间不够的话(例如缩小浏览器)就会出现滚动条,所以我们的内容不会被截断。
缺点:
1、我唯一能想到的就是需要一个额外的空元素(这其实没那么糟,看你自己怎么认为)。
4)这个方式使用一个绝对定位且固定宽高的div,接着这个div被要求拉伸到top:0;bottom:0;,它因为高度被固定而做不到这一点,所以margin:auto;就让它居中了。这个方法类似于常见的使用margin:0 auto;来让块状元素水平居中。
这个方式使用一个绝对定位且固定宽高的div,接着这个div被要求拉伸到top:0;bottom:0;,它因为高度被固定而做不到这一点,所以margin:auto;就让它居中了。这个方法类似于常见的使用margin:0 auto;来让块状元素水平居中。
Html代码
<div id="content">Content here</div>
Css代码
#content {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
height: 240px;
width: 70%;
}
优点:
1、简单。
缺点:
1、不支持IE(但支持IE8 beta)。
2、空间不足的话内容会被截断,不会出现滚动条。
5)这个方法只会居中一行文字。只需要设置line-height等于目标对象的高度,然后文字就居中了。
Html代码
<div id="content">Content here</div>
Css代码
#content {
height: 100px;
line-height: 100px;
}
优点:
1、支持所有的浏览器。
2、空间不足时不会被截断。
缺点:
1、只能用在文本上(不能用在块状元素上)。
2、如果超过一行的话(例如换行)就失效了。