html高度自动居中,CSS解决未知高度的垂直水平居中自适应问题

今天有人问起,晚上试着写出来,供参考; 以下代码兼容主流浏览器IE6、IE7、Firefox、Opera。

从最简单的开始…………

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

这个简单不作过多说明!

复制代码代码如下:

body { text-align:center}

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

this is test.

提示:您可以先修改部分代码再运行

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

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

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

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

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

复制代码代码如下:

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

this is test.

提示:您可以先修改部分代码再运行

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

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

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

复制代码代码如下:

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;} /*这里可以指个宽度试试,是可以自适应的*/

this is test.

this is test.

this is test.

this is test.

this is test.

this is test.

this is test.

this is test.

提示:您可以先修改部分代码再运行

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

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

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

复制代码代码如下:

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;} /*这里可以指个宽度试试,是可以自适应的*/

this is test.

this is test.

this is test.

this is test.

this is test.

this is test.

this is test.

this is test.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值