帐号: 密码:
// 设为首页 // 收藏本站 // 请您留言 // 网址导航
远方教程-满足你的求知欲!
站内搜索:
HTML ASP PHP CSS DIV Dreamweaver Photoshop Word Excel PPT SEO技巧
您当前位置:网站首页 >> HTML入门 >> Div+CSS从入门到精通 >> 阅读文章

CSS网页布局:div水平居中的各种方法

来源:远方教程 作者:远方教程 发布时间:2015-03-03 查看次数:4652 访问[新版]

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

  一、margin:auto 0 与 text-aligh:center
  在现代浏览器(如Internet Explorer 7、Firefox、Opera等)现代浏览器实现水平居中的方法很简单,只要设定到左右两侧的空白为自动即可。意即:

#wrap { margin:0 auto;}
  上面这段代码的意思是说使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.w3.org/1999/xhtml">
 <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.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <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像素。

第1页 第2页 第3页
打印 打印 | 关闭 关闭 评论
相关文章
图片新闻
站内搜索  
搜索
猜您喜欢  
最新更新  
阅读排行  
关于我们 | 联系方式 | 大事记 | 免责声明 | | 给我留言
部分广告源自金山联盟2345联盟 QQ咨询 站长之家QQ群:232617873
Copyright 2024 远方教程 © All Rights Reserved.

回顶部