你好,欢迎访问远方教程PC版!
广告位招租

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

[日期:2015-03-03]   来源:远方教程  作者:远方教程   阅读:4617次[字体: ] 访问[旧版]
 捐赠远方教程 

  在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页
图片展示
 
相关评论
站长推荐