div水平居中的各种方法

在Web标准中的页面布局是使用Div配合CSS来实现的。这其中最常用到的就是使整个页面水平居中的效果,这是在页面布局中基本,也是最应该首先掌握的知识。不过,还是经常会有人问到这个问题,在这里我简单总结一下使用Div和CSS实现页面水平居中的方法:

 

一、margin:auto 0 与 text-aligh:center

  • 上面这段代码的意思是说使wrap这个div到左右两侧的距离自动设置,上下为0(可以为任意)。请在现代浏览器(如Internet Explorer 7、Firefox、Opera等)中运行现在的代码:

  • <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.huaanzn.com/Index.Asp">
     <head>
      <title> new document </title>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
      <style type="text/css">
      div#wrap {
     width:760px;
     margin:0 auto;
     border:1px solid #333;
     background-color:#ccc;
      }
      </style>
     </head> <body>
      <div id="wrap">
      在Firefox等现代浏览器设定页面元素的水平居中,只要指定margin:0 auto;即可
      <pre>
        div#wrap {
     width:760px;
     margin:0 auto; /*这里的0可以任意值*/
     border:1px solid #ccc;
     background-color:#999;
      }
    </pre>
      </div>
     </body>
    </html>

  •   上面的效果很好。但是这在Internet Explorer 6及改正的版本中是不起作用的,不过幸好它有自己的解决办法。在Internet Explorer中text-align属性是可继承的,即在父元素中设置后在子元素中就默认具有了该属性。因此我们可以在body标签中设置text-align属性值为center,这样页面内所有的元素都会自动居中,同时我们还要加一个hook把页面中的文字变成我们习惯的阅读方式——居左对齐。因此我们要如此来写代码:

  • body {text-align:center;}  
    #wrap {text-align:left;} 

  • 这样在Internet Explorer中我们就轻松实现了Div的居中对齐。因此要在所有的浏览器中显示居中的效果,我们就可以这样写我们的代码:

  • body { text-align:center; }  
    #wrap { text-align:left;  
                 margin:0 auto;  

  • <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.huaanzn.com/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.huaanzn.com">
     <head>
      <title> CSS+Div实现水平居中对齐的页面布局 </title>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
      <style type="text/css">
      body { text-align:center; }
      div#wrap {
     text-align:left;
     width:760px;
     margin:0 auto;
     border:1px solid #333;
     background-color:#ccc;
      }
      </style>
     </head> <body>
      <div id="wrap">
      在Firefox等现代浏览器设定页面元素的水平居中,只要指定margin:0 auto;即可
      <pre>
        div#wrap {
     width:760px;
     margin:0 auto; /*这里的0可以任意值*/
     border:1px solid #ccc;
     background-color:#999;
      }  在Internet Explorer 6 及以下的版本中我们还要做以下的设置:
     body { text-align:center; } div#wrap {
     text-align:left;
     }
    </pre>
      </div>
     </body>
    </html>

  •     不过这里有一个前提,就是设置居中的元素要有固定的宽度,比如这里我们设定了为760像素。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值