一.描述
css设置样式时,一对父子元素。当父元素没有上边框(border-top)或者没有上内边距(padding-top)的时候,给子元素设置上外边距,会作用到父元素上。
例子:
<style type="text/css">
#parent{
width: 200px;
height: 200px;
background-color: #00f;
}
#child{
width: 100px;height: 100px;
background-color: #f00;
margin-top: 40px;
}
</style>
二.解决方法:
1.给父元素加上边框,弊端:增加了父元素实际占据高度
2.给父元素添加上内边距,弊端:增加了父元素实际占据高度
3.给父元素设置overflow:hidden/auto 元素如果想溢出显示,就冲突了
4.在该子元素的前面,添加一个空的元素,比如<table></table>(推荐使用)
效果:
<style type="text/css">
#parent{
width: 200px;
height: 200px;
background-color: #00f;
}
#child{
width: 100px;height: 100px;
background-color: #f00;
margin-top: 40px;
}
</style>
</head>
<body>
<div id="parent">
<table></table>
<div id="child"></div>
</div>
</body>