利用CSS使Div水平垂直居中

通常在制作网站首页时需要使页面内容在水平和垂直方向上都居中。表格布局时代常用的方法是内容之前添加换行。实际上通过CSS有更方便的办法。

 

<style type="text/css">
body 
{
  background
:#ccc;
  margin
:0;
  padding
:0;
}

#wrap 
{
  position
:absolute;
  width
:500px;
  height
:100px;
  left
:50%;
  top
:50%;
  margin-left
:-250px;
  margin-top
:-50px;
  background
:#fff;
  color
:#999;
}
</style>

<body>
  
<div id="wrap">Test</div>
</body>

 

 

 

原理很简单:将left和top设置为50%来定位div到浏览器中央,再将margin-left和margin-top值设置为宽和高的一半,使div居中显示。

posted on 2010-03-19 16:22  依然微笑。。  阅读(166)  评论(0编辑  收藏  举报

导航