Heim  >  Artikel  >  Web-Frontend  >  为什么margin-top不是作用于父元素_html/css_WEB-ITnose

为什么margin-top不是作用于父元素_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 11:41:231039Durchsuche

为什么margin-top不是作用于父元素:
至于margin-top属性的基本用法再简单不过,那就是设置一个对象的上外边距,看下面的代码实例:

<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><meta name="author" content="http://www.51texiao.cn/" /><title>蚂蚁部落</title><style type="text/css"> * {   margin:0px;   padding:0px; } div {   width:100px;   height:100px;   background-color:green;   margin-top:50px; } </style> </head> <body>   <div></div> </body> </html>

以上代码可以将div的上边距设置为50px,一切运行良好,没有任何问题,再来看下一段代码:

<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><meta name="author" content="http://www.51texiao.cn/" /><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> <div id="parent">   <div id="children"></div> </div> </body> </html>

以上代码的初衷是让子元素的顶部距离父元素50px,但是事实上却并没有实现预期的效果,而是子元素顶部紧贴父元素,并且margin-top好像转移给了父元素,让父元素产生上外边距。这其实是一个典型的外边距合并问题,但是并非所有的浏览器都会产生这种情况,一般标准浏览器都会出现此现象,而IE6和IE7在此状态下不会出现外边距合并现象。上外边距合并出现的条件:
1.父元素的上边距与子元素的上边距之间没有border。
2.父元素的上边距与子元素的上边距之间没有非空内容。
3.父元素的上边距与子元素的上边距之间没有padding。
3.父元素和子元素中没有设置定位属性(除static和relative)、overflow(除visible)和display:inline-block等。
4.父元素或者资源都没有浮动。
注意:以上条件必须都要满足才可以。那么解决此中情况的方式也很简单,只要破坏上面的一种情况就可以了。

原文地址是:http://www.51texiao.cn/div_cssjiaocheng/2015/0501/506.html

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn