下面我们来看一款利用css实现div中内容居中的方法,下面整理了三种css实现网页内容整体居中方法,希望对各位朋友会有所帮助。
例
代码如下
复制代码
<!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=utf-8″ />
<title>内容居中</title>
<style type=”text/css”>
.box{ width:600px; height:100px; border:1px solid #000; vertical-align:middle; display:table-cell;}
</style>
</head>
<body>
<div class=”box”>
<p>无标题文档无标题文档无标题文档无标题文档无标题文档无标题文档无标题文档无标题文档无标题文档</p>
</div>
</body>
</html>
测试文件index.html的代码其中外部的style.css文件地址请自己更换
代码如下
复制代码
<html>
<head><link href="style.css" rel="Stylesheet" type="text/css" /></head>
<body>
<div id="wrap"></div>
</body>
</html>
方法一(style.css):
代码如下
复制代码
*{margin:0;padding:0;}/*顶部对齐*/
#wrap
{
position:relative;
width:988px;
margin-left:50%;
left:-494px;
height:1200px;
border:solid 1px red;
}
评论:此方法是先定好内容的宽度,然后向左距离整个浏览器的50%,再向左拉回内容宽度的一半
方法二(style1.css):
代码如下
复制代码
*{margin:0;padding:0;}
body{text-align:center;}
#wrap
{
position:relative;
margin:0 auto;
width:988px;
height:1200px;
text-align:left;
border:solid 1px red;
}
评论:此方法是先定好内容的宽度,然后body里面内容居中,然后容器里面内容靠左,注意 margin:0 auto;是为了兼容其他浏览器
方法三(style2.css):
代码如下
复制代码
*{margin:0;padding:0;}
#wrap
{
position:relative;
width:988px;
margin-left:-494px;
left:50%;
height:100%;
border:solid 1px red;
}
评论:和方法一类似,可以对比方法一看