margin-top塌陷:两个盒子嵌套时,设置内部盒子的margin-top值时会直接加到外边的盒子上,导致内部盒子margin-top设置失败,有三种解决方法,第三种是最常用,方法如下:
1、给外边盒子设置border值,这样内部盒子就可以设置margin-top值
2、使用overflow元素溢出属性,hidden内容被修剪,修剪内容不显示(不建议应用时使用,因为有的格式需要设置溢出,不能hidden)
3、使用伪元素类 :.clearfix:before{
content:” “;
display:table; 类似于第一种给外部盒子加边框方式,是使用较多的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>margin-top塌陷</title>
<!--在两个盒子嵌套时候,内部的盒子设置的margin-top会加到外边的盒子上,导致内部的盒子margin-top设置失败-->
<style type="text/css">
.clearfix:before{
content:" ";
display:table;
} /*第三种解决margin-top塌陷的方法,如上使用伪元素类,类似于第一种给盒子加边框,display:table作为表格显示,让盒子作为表格显示*/
.con{
width:200px;
height:200px;
background-color: gold;
/*border: 1px solid black;
第一种解决塌陷的方法,给外面盒子加边框*/
/*overflow: hidden;第二种解决margin-top塌陷方法,利于overflow元素溢出属性设置,overflow: hidden内容被修剪,修剪内容不可见*/
}
.box{
width:120px;
height:50px;
background-color:green;
margin-top:75px;
}
</style>
</head>
<body>
<div class="con clearfix">
<div class="box"></div>
</div>
</body>
</html>
版权声明:本文为weixin_74239923原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。