<div id="parent"> <div id="son"></div> </div> <style> body{ margin: 0; padding: 0; background-color: grey; } #parent{ width: 200px; height: 200px; background-color: red; } #son{ width: 100px; height: 100px; background-color: green; margin-top: 50px; } </style>
页面效果:
这是margin外边距坍塌致使的,按照css规范,两个相邻的元素之间的margin值会共用较大的那一个,而若是没有上边框或上内间距,嵌套的元素之间和同级的元素同样知足使用这个规范的条件,父元素会拥有子元素同样的上外边距。要解决这个问题其实也很是简单,这里给出四种不一样的解决方法。css
<div id="parent"> <div id="son"></div> </div> <style> body{ margin: 0; padding: 0; background-color: grey; } #parent{ width: 200px; height: 200px; background-color: red; overflow: hidden; } #son{ width: 100px; height: 100px; background-color: green; margin-top: 50px; } </style>
效果如图:
html
<div id="parent"> <div id="son"></div> </div> <style> body{ margin: 0; padding: 0; background-color: grey; } #parent{ width: 200px; height: 200px; background-color: red; border-top: 1px solid transparent; } #son{ width: 100px; height: 100px; background-color: green; margin-top: 50px; } </style>
效果如图:
git
<div id="parent"> <div id="son"></div> </div> <style> body{ margin: 0; padding: 0; background-color: grey; } #parent{ width: 200px; height: 200px; background-color: red; float: left; } #son{ width: 100px; height: 100px; background-color: green; margin-top: 50px; /* float: left; */ /* 浮动加在子元素上也能够 */ } </style>
效果如图:
github
<div id="parent"> <div id="son"></div> </div> <style> body{ margin: 0; padding: 0; background-color: grey; } #parent{ width: 200px; height: 200px; background-color: red; padding-top: 1px; } #son{ width: 100px; height: 100px; background-color: green; margin-top: 50px; } </style>
效果如图:
学习
以上为所有内容,感谢阅读。
本博文仅为学习记录和分享交流,若有错漏,还请帮忙指出,也欢迎更多补充,不胜感激。spa
GitHub地址:https://github.com/ljxlijiaxin.code