margin相对的元素在不同的情况下有所不同:
如果父元素在子元素的margin的同向上有padding或border的话,子元素的margin相对于父元素,否则相对于父元素以外的元素。
我们还是看例子吧:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>margin</title>
<style type="text/css">
.parent{width: 300px;line-height: 1.8;}
.sample{height: 150px;background-color: pink;}
.sb{width: 300px;height: 150px;background-color: #0ff;}
.sample{margin-bottom: 50px;}
</style>
</head>
<body>
<div class="parent">
<div class="sample">sample</div>
</div>
<div class="sb">after</div>
</body>
</html>
此时父元素在子元素的margin的同向上(bottom)没有padding或border,子元素的margin相对于父元素以外的元素。
效果如图:
这个时候,如果给父元素添加下边框(与子元素margin同向)的话,css为:.parent{border-bottom: 5px solid red;}
那么子元素的margin相对于父元素。效果如下:
如果我们不加边框而是增加下内边距(与子元素margin同向)的话,css为:.parent{padding-bottom: 50px;}
那么子元素的margin相对于父元素(为了看到内边距效果,可以在父元素上设 .parent{outline: 1px dashed red;})。效果如下: