当父元素当中有一个子元素的时候,子元素设置margin-top或者margin-bottom的时候会不起作用,也就是子父元素之间并没有产生间距,但是这个值作用到了父元素的身上。具体代码如下:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>标题</title> <meta name="keywords" content=""> <meta name="description" content=""> <style> .outer{ background:#ccc; } .inner{ background:red; margin-top:20px; } </style> </head> <body> <div class="outer"> <div class="inner">我是子元素</div> </div> </body> </html>
出现的效果如下:
可以看到我父元素设置的是灰色的背景,子元设置的红色背景,子元素设置了margin-top值,按照常理来说子父级之间应该会出现一个灰色的间隙,但是并没有,然后当我把审查元素打开看到这个值作用到了父元素的身上,所以父元素和上边产生了20px的间距。
有几种方法可以解决:
(1)当父元素设置了padding-top,或者border-top之后,子元素的margin-top值会生效,具体如下:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>标题</title> <meta name="keywords" content=""> <meta name="description" content=""> <style> .outer{ background:#ccc; /* border-top:5px solid green; */ padding-top:10px; } .inner{ background:red; margin-top:20px; } </style> </head> <body> <div class="outer"> <div class="inner">我是子元素</div> </div> </body> </html>设置了border-top之后:
设置了padding-top之后:
可以看到当父元素设置了border-top之后子元素的margin值起到了作用,父元素设置padding-top之后也起到了作用,同样是子元素设置了margin-bottom之后也会出现叠加到父元素身上的情况,同样border-bottom和padding-bottom也会阻断这种叠加。padding值不能为0;
(2)当父元素设置了height,min-height,max-height,会截断margin-bottom的叠加
例如这种情况:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>标题</title> <meta name="keywords" content=""> <meta name="description" content=""> <style> .outer{ background:#ccc; } .inner{ background:red; margin-bottom:20px } .nextOuter{ background:blue; } </style> </head> <body> <div class="outer"> <div class="inner">我是子元素</div> </div> <div class="nextOuter"> 父元素的兄弟元素 </div> </body> </html>
出现的情况如下:
可以看到和上面一样子元素的margin-bottom值叠加到了父元素上,使得父元素与相邻元素出现了空隙。
解决方法:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>标题</title> <meta name="keywords" content=""> <meta name="description" content=""> <style> .outer{ background:#ccc; height:18px;/* 可以阻断叠加到父元素的情况 */ } .inner{ background:red; margin-bottom:20px } .nextOuter{ background:blue; } </style> </head> <body> <div class="outer"> <div class="inner">我是子元素</div> </div> <div class="nextOuter"> 父元素的兄弟元素 </div> </body> </html>
但是height只能阻断margin-bottom,并不能阻断maigin-top
<!doctype html> <html> <head> <meta charset="utf-8"> <title>标题</title> <meta name="keywords" content=""> <meta name="description" content=""> <style> .outer{ background:#ccc; height:18px;/* 可以阻断叠加到父元素的情况 */ } .inner{ background:red; margin-bottom:20px; margin-top:20px; } .nextOuter{ background:blue; } </style> </head> <body> <div class="nextOuter"> 父元素的兄弟元素 </div> <div class="outer"> <div class="inner">我是子元素</div> </div> <div class="nextOuter"> 父元素的兄弟元素 </div> </body> </html>
同时设置了margin-top和margin-bottom,并且设置了height之后,如下:
(3)多个相邻的没有设置高度的空元素,margin-bottom和margin-top会相互叠加
(4)脱离文档流的,也不会出现叠加,比如浮动的元素。
(5)margin-top和margin-bottom对行元素无效。