您的位置:首页 > 其它

div垂直水平自适应居中解决方法

2013-08-09 16:12 239 查看
以下代码兼容主流浏览器IE6、IE7、Firefox、google、Opera。

从最简单的开始…………

一、如何让一个DIV水平居中?

这个简单不作过多说明!

代码如下:

<style>

body { text-align:center}

#info{ margin:0 auto; width:500px; text-align:left; border:1px solid #3333FF}

</style>

</head>

<body>

<div id="info">this is test.</div>

</body>

二、DIV已知高度,如何让他水平加垂直居中?

如果想水平加垂直居中的DIV已知高度和宽度,是最好办的了!

1、先让这个DIV绝对定位;

2、让他距离上边50%,左边50%;这会这个DIV的左上角这个点就是窗口的正中间;

3、因为已经知道了这个DIV的高和宽了,那么再从这里点向左移动总宽的一半就可以了,也就是200PX; 向上呢也同理;

代码如下:

<style>

#info{top:50%;left:50%; position:absolute; width:600px; height:400px; margin:-200px -300px; border:1px solid #f00;}

</style>

<div id="info">this is test.</div>

三、DIV不知道高度怎么让他水平和垂直居中?

这个比较麻烦,用上边的方法的一半再加一些代码才能实现!

首先我先按上边代码意思接着写,注意,下边的代码是我写好的第一步,只支持IE6和IE7,不过先看一下!

代码如下:

<style>

body {padding:0; margin:0; }

#infoBox{ position:absolute; top:50%; width:100%; text-align:center;}

#info{position:relative; top:-50%; right:0; border:1px solid #333399; text-align:center;} /*这里可以指个宽度试试,是可以自适应的*/

</style>

<div id="infoBox">

<div id="info">

this is test.

this is test.

this is test.

this is test.

this is test.

this is test.

this is test.

this is test.

</div>

</div>

那么,如果让Firefox再支持一下就可以,对吧!所以接着写!

标准浏览器可将父级元素显示方式设定为display: table;,内部子元素设为display:table-cell 和vertical-align;使其垂直居中,但非标准浏览器是不支持;也就是说这样设完后IE6是不支持的,但FIREFOX和IE是支持的;

我用的是最笨的办法,从上往下一级级覆盖;

代码如下:

<style>

body {padding:0; margin:0; }

/*这些是专用FIREFOX写的,注意IE7也认识*/

html,body{ height:100%;}

#infoBox[id]{text-align:center; width:100%; height:100%; display:table;}

#info[id]{ display:table-cell; vertical-align:middle;} /*这里可以指个宽度试试,是可以自适应的*/

/*专为IE6写的*/

*html #infoBox{ position:absolute; top:50%; width:100%; text-align:center; display:block; height:auto}

*html #info{position:relative; top:-50%; border:1px solid #333399; text-align:center;} /*这里可以指个宽度试试,是可以自适应的*/

/*这理是专用IE7写的,注意[id]要加上,不然优先JI没有最上边那段NB*/

*+html #infoBox[id]{ position:absolute; top:50%; width:100%; text-align:center; display:block; height:auto}

*+html #info[id]{position:relative; top:-50%; border:1px solid #333399; text-align:center;} /*这里可以指个宽度试试,是可以自适应的*/

</style>

<div id="infoBox">

<div id="info">

this is test.

this is test.

this is test.

this is test.

this is test.

this is test.

this is test.

this is test.

</div>

</div>

</html>

这时你又会发现,在IE和FIREFOX中怎么效果不一样呢?FIREFOX中没有那个边框;对的…… 如果你看一下info这个DIV,他其它是占高度100%的;这时的同一个布局在不同的浏览器是展示出来隐在效果已经完全不一样了;那么怎么办? 所以,再用最后一个办法;再加一个空的DIV就行了,我起了个好名字,叫tnnd; 最后的效果如下;

后边这种是最麻烦的,重点在于IE67和FIREFOX中间的差别和他们相互之间是如何的一些关系;我看过很多关于这个问题的解决方法,都不是特别的理想,希望这种方法能解决大部分的问题!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: