代码改变世界

网页居中

2010-02-04 22:19  观海看云  阅读(220)  评论(0编辑  收藏  举报
我看到有些网页在IE里是居中的,可是到了Firefox里就靠左了,其实这个问题很简单,看下面这段代码:

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>网页居中</title>
<style>
        body
        {
                text-align:center;
        }
       
        div.window
        {
                border:#330066 solid 1px;
                width:800px;
                height:700px;
                margin-left:auto;
                margin-right:auto;
        }
       
</style>
</head>

<body>
        <div class="window"></div>
</body>
</html>

复制上面的代码,保存为index.html,用浏览器浏览下效果,可以看到窗口永远是居中的
原理是在你要居中的窗口(该例是window)的样式中添加margin-left:auto;margin-right:auto;让它左右空隙都自动,这样它就能自动居中对齐了