时间:2021-07-01 10:21:17 帮助过:57人阅读
- <!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><meta name="author" content="http://www.softwhy.com/" /><title>为什么margin-top不是作用于父元素</title><style type="text/css"> *
- {
- margin:0px;
- padding:0px;
- } p
- {
- width:100px;
- height:100px;
- background-color:green;
- margin-top:50px;
- }
- </style>
- </head>
- <body>
- <p></p>
- </body>
- </html>
以上代码可以将p的上边距设置为50px,一切运行良好,没有任何问题,再来看下一段代码:
- <!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><meta name="author" content="http://www.softwhy.com/" /><title>蚂蚁部落</title><style type="text/css"> #parent
- {
- width:200px;
- height:200px;
- background-color:red;
- } #children
- {
- width:60px;
- height:60px;
- background-color:green;
- margin:0px auto;
- margin-top:50px;
- }
- </style>
- </head>
- <body>
- <p id="parent">
- <p id="children"></p>
- </p>
- </body>
- </html>
以上代码的初衷是让子元素的顶部距离父元素50px,但是事实上却并没有实现预 期的效果,而是子元素顶部紧贴父元素,并且margin-top好像转移给了父元素,让父元素产生上外边距。这其实是一个典型的外边距合并问题,但是并非 所有的浏览器都会产生这种情况,一般标准浏览器都会出现此现象,而IE6和IE7在此状态下不会出现外边距合并现象。上外边距合并出现的条件:
1.父元素的上边距与子元素的上边距之间没有border。
2.父元素的上边距与子元素的上边距之间没有非空内容。
3.父元素的上边距与子元素的上边距之间没有padding。
3.父元素和子元素中没有设置定位属性(除static和relative)、overflow(除visible)和display:inline-block等。
4.父元素或者资源都没有浮动。
注意:以上条件必须都要满足才可以。那么解决此中情况的方式也很简单,只要破坏上面的一种情况就可以了。
更多关于外边距合并内容可以参阅margin外边距合并详解一章节。
以上就是margin-top不是作用于父元素的原因的详细内容,更多请关注Gxl网其它相关文章!