一、margin表示元素的外边距,兼容性不用多说,老牌子了,全兼容。
二、用法说明
1、语法:
margin:auto | length | % inherit;
值 | 描述 |
---|---|
auto | 浏览器计算外边距。 |
length | 规定以具体单位计的外边距值,比如像素、厘米等。默认值是 0px。 |
% | 规定基于父元素的宽度的百分比的外边距。 |
inherit | 规定应该从父元素继承外边距。 |
形如:margin:5px 10px 15px 20px;
依次表示 上右下左
上 margin-top 5px
右 margin-right 10px
下 margin-bottom 15px
左 margin-left 20px
缺省情况下 margin:5px;
表示 上下左右都是5px
缺省情况下 margin:5px 10px;
表示 上下是5px,左右是10px
缺省情况下 margin:5px auto 10px;
表示 上是5px,左右是auto,下为10px
默认值: | 0 |
---|---|
继承性: | no |
版本: | CSS1 |
JavaScript 语法: | object.style.margin="10px 5px" |
2、使用注意事项:
块级元素的垂直相邻外边距会合并
代码示例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>margintest</title>
<style>
body{
margin: 0;
padding:0;
}
#content{
width:300px;
height:300px;
background-color: red;
margin: 10px 5px 15px 20px;
}
#content1{
width:300px;
height:300px;
background-color: red;
margin: 10px 5px 15px 20px;
}
#inner{
margin: 15px 5px 15px 20px;
background-color: #4169E1;
width:100px;
height: 100px;
}
</style>
</head>
<body>
<div id='content'>
<div id='inner'></div>
</div>
<div id='content1'>
</div>
</body>
</html>
行内元素实际上不占上下外边距(个别除外如img等等),左右外边距不会合并。
代码示例:
<span style="font-family:SimHei;font-size:18px;"><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>margintest</title>
<style>
body,img{
margin: 0;
padding:0;
}
img{
outline-width:0px;
vertical-align: top;/**垂直方向消除图片与图片之间的间隔***/
float:left;/**水平方向消除图片与图片的间隔***/
}
#img1,#span1{
background-color:blue;
margin:5px 10px 15px 20px;
}
#img2,#span2{
background-color:red;
margin:5px 10px 15px 20px;
}
</style>
</head>
<body>
<img id='img1' src='award.png'>
<img id='img2' src='think.png'>
<div>
<span id='span1'>111111111111111111111</span>
<span id='span2'>222222222222222222222</span>
</div>
</body>
</html> </span>
浮动元素的外边距也不会合并,相信上面的例子已经很明显了。同上,在使用时一定要注意。
三、margin的解析逻辑
margin的基本特性和基本写法非常简单,但是margin产生边距的逻辑是什么呢?margin的top、right、bottom、left都是以什么为基准来促使box model形成?为了形象,易懂的对margin的逻辑进行说明,下面讲解的过程中,将引入W3C上没有的参考线的说法。何谓参考线?参考线就是margin移动的基准点,此基准点相对于box是静止的。而margin的数值,就是box相对于参考线的位移量。
在margin中top、right、bottom、left的参考线并不一致为一类,而是分为了两类参考线,top和left的参考线属于一类,right和bottom的参考线属于另一类。那他们到底各以什么为参考线呢?top以containing block的content上边或者垂直上方相连元素margin的下边为参考线垂直向下位移;left以containing block的content左边或者水平左方相连元素margin的右边为参考线水平向右位移。right以元素本身的border右边为参考线水平向右位移;bottom以元素本身的border下边为参考线垂直向下位移。从上我们可以看到top和left都是以外元素为参考,而right和bottom以本元素为参考。上面的位移方向是指margin数值为正值时候的情形,如果是负值则位移方向相反。
参考文章 http://www.jb51.net/css/66198.html漂切一张图,如下说明