今天在CSS3练习弹性盒子中想起了margin的塌陷问题。在这里回忆一下…
margin 塌陷是在父级相对于浏览器进行定位时但子级没有相对于父级定位,子级相对于父级就像塌陷了一样,父子嵌套元素垂直方向的 margin,父子元素是结合在一起的,他们两个会取其中最大的值。
1)当两个盒子垂直并列在一起时(不常见)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
.box1{
width: 200px;
height: 200px;
background: yellowgreen;
}
.box2{
width: 200px;
height: 200px;
background: gray;
}
</style>
</head>
<body>
<div class="box1">box1</div>
<div class="box2">box2</div>
</div>
</body>
</html>
如果我将box1的margin-bottom设置为80px,而box2的margin-top属性设置为50px,那么box1与box2是相距130px还是什么呢?对于大多数初学者而言,一眼觉得是130px,而非80px。这就是margin的塌陷问题。
<div class="box1">box1</div>
<div class="box2">box2</div>
*{
margin: 0;
padding: 0;
}
.box1{
width: 200px;
height: 200px;
background: yellowgreen;
margin-bottom: 80px;
}
.box2{
width: 200px;
height: 200px;
margin-top: 50px;
background: gray;
}
我们来看看效果
2)一个盒子里面嵌套另一个盒子时,在里面的盒子添加margin属性(常见)
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
.box1{
width:400px;
height:400px;
background: #f40;
}
.box2{
width:200px;
height:200px;
margin-top: 20px;
background: #0ff;
}
</style>
</head>
<body>
<div class="box1">
<div class="box2"></div>
</div>
</body>
</html>
效果呢,看了会不会很惊讶呢…
其实吧,这明显是margin塌陷。
margin-top:20px;加到box1或者box2效果一样。那么怎么才能将margin他先解决呢??
我在全网搜了搜,一共以下三种方法:
1.在父级盒子加border属性使box2不再与box1贴合
.box1{
width:400px;
height:400px;
border:1px solid black;
background: #f40;
}
效果呢,就变成我们一开始想象的那样。
2.为父级盒子添加overflow:hidden;position: absolute;float: left; display:inline-block;
3.为父级盒子设定padding值。
其实这三种方法的共同点都是使box2与box1不贴合。促使子级盒子相对于父级定位。
感觉学到点东西的,麻烦点个赞,关注一波也可以。如果有错,请评论或者私信我哈!!!