这里向大家描述一下CSS盒模型(BoxModel)的用法,由于浏览器设计上的问题,不同浏览器显示效果会有些不同。左右Margin加倍的问题当box为float时,IE6中box左右的margin会加倍。
CSS盒模型(BoxModel)详解
width和height定义的是Content部分的宽度和高度,paddingbordermargin的宽度依次加在外面。背景会填充padding和content部分。但是由于浏览器设计上的问题,不同浏览器显示效果会有些不同。左右Margin加倍的问题当box为float时,IE6中box左右的margin会加倍。
W3C定义的盒模式如下:

width和height定义的是Content部分的宽度和高度,paddingbordermargin的宽度依次加在外面。背景会填充padding和content部分。
但是由于浏览器设计上的问题,不同浏览器显示效果会有些不同。
左右Margin加倍的问题
当box为float时,IE6中box左右的margin会加倍。比如:
ExampleSourceCode
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlnshtmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttp-equivmetahttp-equiv="Content-Type"
content="text/html;charset=gb2312"/>
<title>www.52css.com</title>
<style>
.outer{
width:500px;
height:200px;
background:#000;
}
.inner{
float:left;
width:200px;
height:100px;
margin:5px;
background:#fff;
}
</style>
</head>
<body>
<divclassdivclass="outer">
<divclassdivclass="inner"></div>
<divclassdivclass="inner"></div>
</div>
</body>
</html>
左面的inner的左面margin明显大于5px。
这时候,定义inner的display属性为inline。
外层box自动计算高度的问题
根据W3C定义,没有float属性的外层box不会自动计算高度,要计算高度,必须在内层最后一个box加入clear:both。
Opera、netscape、mozilla等不会计算外层box高度,但是微软ie6会自动计算外层高度。比如:
ExampleSourceCode
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlnshtmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttp-equivmetahttp-equiv="Content-Type"
content="text/html;charset=gb2312"/>
<title>www.52css.com</title>
<style>
.outer{
width:600px;
background:#000;
}
.inner1{
float:left;
width:200px;
height:100px;
margin:5px;
background:red;
}
.inner2{
float:left;
width:200px;
height:100px;
margin:5px;
background:yellow;
}
</style>
</head>
<body>
<divclassdivclass="outer">
<divclassdivclass="inner1"></div>
<divclassdivclass="inner2"></div>
</div>
</body>
</html> 居中问题
需要定义元素的宽,并且定义横向的margin,如果你的布局包含在一个层(容器)中,就象这样:
你可以这样定义使它横向居中:
ExampleSourceCode
#wrap{
width:760px;/*修改为你的层的宽度*/
margin:0auto;
}
但是IE5/Win不能正确显示这个定义,我们采用一个非常有用的技巧来解决:在外层用text-align属性。就象这样:
ExampleSourceCode
#outer{
text-align:center;
}
#wrap{
width:760px;/*修改为你的层的宽度*/
margin:0auto;
text-align:left;
}