第一章:CSS中margin重叠问题
文章目录
前言
在web开发中很多前端初学者小伙伴们常常会遇到各种外边距合并的问题,比如我明明设置了margin-top为什么没有起作用,为什么外边距的值和我设置的值不一样等等,这篇文章为你解释什么是外边距合并,以及如何解决这个问题。
一、margin重叠是什么?
首先我们要知道什么是外边距合并,也就是margin重叠,指的是块级元素的上边距(margin-top)与下外边距(margin-bottom)合并为单个外边距,这样的现象被称为“margin重叠”。
二、出现场景及解决办法
1.相邻兄弟元素的margin合并
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.div1 {
width: 100px;
height: 100px;
background-color: aqua;
margin-bottom: 20px;
}
.div2 {
width: 100px;
height: 100px;
background-color: aquamarine;
margin-top: 30px;
}
</style>
</head>
<body>
<div class="div1"></div>
<div class="div2"></div>
</body>
</html>
我们以为的效果:
实际上的效果:
解决办法:
- 设置display值为inline-block
.div2 {
width: 100px;
height: 100px;
background-color: aquamarine;
margin-top: 30px;
display: inline-block;
}
- 设置浮动
.div2 {
width: 100px;
height: 100px;
background-color: aquamarine;
margin-top: 30px;
float:left;
}
2.父元素和子元素之间的margin合并
代码如下(示例):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.div1 {
width: 100px;
height: 100px;
background-color: chartreuse;
margin-bottom: 20px;
}
.father {
width: 100px;
height: 100px;
background-color: blanchedalmond;
}
.son {
width: 100px;
height: 100px;
width: 100%;
height: 40px;
background-color: brown;
margin-top: 30px;
}
</style>
</head>
<body>
<div class="div1">
</div>
<div class="father">
<div class="son">
</div>
</div>
</body>
</html>
我们想要的效果:
实际的效果:
解决办法:
- 设置display值为inline-block
.father {
width: 100px;
height: 100px;
background-color: blanchedalmond;
margin-top: 10px;
display:inline-block;
}
- 设置定位,子元素为绝对定位,父元素为相对定位
.father {
width: 100px;
height: 100px;
background-color: blanchedalmond;
margin-top: 10px;
position:relative;
}
.son {
width: 100px;
height: 100px;
width: 100%;
height: 40px;
background-color: brown;
margin-top: 30px;
position: absolute;
}
- 设置浮动
.son {
width: 100px;
height: 100px;
width: 100%;
height: 40px;
background-color: brown;
margin-top: 30px;
float: left;
}
- 触发一个BFC
.father {
width: 100px;
height: 100px;
background-color: blanchedalmond;
margin-top: 10px;
overflow: hidden;
}
- 给父元素添加边框
.father {
width: 100px;
height: 100px;
background-color: blanchedalmond;
border:1px solid black;
}
三、margin的计算方式
- 如果是两个正数 选取最大的
- 如果是两个复数 选取绝对值最大的
- 如果是一正一负 则为相加和