1.父子元素外边距合并
嵌套的两个元素,当给子元素设置margin值时,父子元素一起向下移动,子元素会越级。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
.outer{
width: 100px;
height: 100px;
background-color: blue;
/* border: 1px solid wheat; */
/* overflow: hidden; */
/* float: left; */
/* display: inline-block; */
}
.inner{
width: 40px;
height: 40px;
background-color: chartreuse;
margin-top: 20px;
/* float: left; */
/* display: inline-block; */
}
</style>
</head>
<body>
<div class="outer">
<div class="inner">
</div>
</div>
</body>
</html>
效果如图:
我们想要的效果:
解决方法如下:
- 给父元素设置边框,明确界限。
- 给父元素设置overfloat:hidden属性。
- 给子级或父级一方设置浮动,float。
- 给子级或父级一方设置display:inline-block;
兄弟元素
垂直方向上,当给两个元素设置margin时,外边距会发生合并,并且会以margin值大的准。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
.div1{
width: 200px;
height: 200px;
background-color: violet;
margin-bottom: 50px;
}
.div2{
width: 200px;
height: 200px;
background-color: rgb(23, 192, 127);
margin-top: 100px;
}
</style>
</head>
<body>
<div class="div1"></div>
<div class="div2"></div>
</body>
显示效果图:
div1的margin
div2的margin
如图所示,两个元素的margin值会发生合并,并且两个元素间距显示为大的margin值,而不会发生叠加显示为150px的间距宽度。
新手小白,文章仅供参考学习,如有错误,欢迎大家指正,相互学习!!!