DIV、UL、li、image水平竖直居中代码大全(for ie firefox opera)~

来源:互联网 发布:网络最流行的话语 编辑:程序博客网 时间:2024/06/07 07:48

1、DIV在整个body中水平居中:

#DivComment{
position:absolute;
top: 90%;
left: 45%;
width:40%;
margin:0 0 0 -240px;
padding: 10px 10px 0px 0px;
}

效果见:这里的评论层

2、DIV在另一个DIV中水平居中:

#div1{
TEXT-ALIGN: center;
}
#div2{
MARGIN-RIGHT: auto;
MARGIN-LEFT: auto;
height:200px;
background:#F00;
width:400px;
}

在要居中的div的父级元素(未必是div,可以是ul、li等)中设置TEXT-ALIGN: center;即可实现此div居中,但仅限于IE6&IE7。在此div中加上MARGIN-RIGHT: auto; MARGIN-LEFT: auto;或者margin: 0 auto;即可实现在firefox中也居中。

3、UL居中和li水平居中:

其实任何居中,只要是web元素,可加上id属性的都可以使用上面的方法。只是要记住需把ul、li的宽度设置一下才,最好加个背景色才可以看出是否居中。否则ul、li默认是一条撑满div的"楼梯",是看不出是否居中的。

4、image居中:

也可用上述方法,但我发现有时直接用最简单的<div align=center><img src="xxx.jpg"></div>,维护起来更方便

5、DIV垂直居中

可参考以下文章:
div+css实现Firefox和IE6兼容的垂直居中
CSS如何使DIV层居中之我见
css中如何使div居中(垂直水平居中)

<html>
<body>
<div style="display: table-cell; vertical-align: middle; height: 200px; border: 1px solid red;">
<p>垂直居中,Firefox only</p>
<p>垂直居中,Firefox only</p>
<p>垂直居中,Firefox only</p>
</div>
<div style="border: 1px solid red; height: 200px; position: relative;">
<div style="position: absolute; top: 50%;">
<div style="position: relative; top: -50%;">
<p>垂直居中,IE6 only</p>
<p>垂直居中,IE6 only</p>
<p>垂直居中,IE6 only</p>
</div>
</div>
</div>
<div style="border: 1px solid red; height: 200px; position: relative; display: table-cell; vertical-align: middle;">
<div style="position: static !important; position: absolute; top: 50%;">
<div style="position: relative; top: -50%;">
<p>垂直居中,Firefox IE6 only</p>
<p>垂直居中,Firefox IE6 only</p>
<p>垂直居中,Firefox IE6 only</p>
</div>
</div>
</div>
</body>
</html>

再来俩 水平 垂直居中的代码。。。

1. <div style="width:300px;height:300px;text-align:center;vertical-align:middle;line-height:300px;border:1px solid #ccc;display:table-cell">
<img src="http://pic.yupoo.com/aliued/0688751b2d41/square.jpg" style="_margin-top: expression((300-this.height)/2);" />
</div>

2. <style>
.box {
/*非IE的主流浏览器识别的垂直居中的方法*/
display: table-cell;
vertical-align:middle;

/*设置水平居中*/
text-align:center;

/* 针对IE的Hack */
*display: block;
*font-size: 175px;/*约为高度的0.873,200*0.873 约为175*/
*font-family:Arial;/*防止非utf-8引起的hack失效问题,如gbk编码*/

width:200px;
height:200px;
border: 1px solid #eee;
}
.box img {
/*设置图片垂直居中*/
vertical-align:middle;
}
</style>
<div class="box">
<img src="http://pics.taobao.com/bao/album/promotion/
taoscars_180x95_071112_sr.jpg" />
</div>

代码均来自网上!