先看两个Bug
第一个Bug:margin塌陷。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="style1211.css">
</head>
<body>
<div class="wrapper">
<div class="content"></div>
</div>
</body>
</html>
*{
margin: 0;
padding: 0;
}
.wrapper{
margin-top: 100px;
margin-left: 100px;
width: 100px;
height: 100px;
background-color: orange;
}
.content{
/*margin-left: 50px;*//*第一步增加此行代码*/
/*margin-top: 50px;*//*第二步增加此行代码*/
width: 50px;
height: 50px;
background-color: gray;
}
可以看到第一步增加的代码子元素移动了,第二步增加的代码没有让子元素移动,这个Bug叫margin塌陷(子集相对于父级没有顶棚一样)。
怎么解决这个Bug?
方案一:(不建议使用,但能解决效果)父级增加一个顶棚,加一个可视化的border-top。
.wrapper{
margin-top: 100px;
margin-left: 100px;
width: 100px;
height: 100px;
background-color: orange;
border-top: 1px solid red;/*父级增加此行代码*/
}
方案二:使用BFC。
BFC(Block Format Context)块级格式化上下文。每个盒子的渲染规则是一定的,设置成BFC后改变了盒子的渲染规则。
改变的规则后就解决了margin塌陷。
如何触发一个盒子的BFC?下面是几种常用的方法。
- position:absolute
- float:left/right
- display:inline-block
- overflow:hidden 溢出父元素部分隐藏。
下面就是触发父级BFC解决margin塌陷。
.wrapper{
margin-top: 100px;
margin-left: 100px;
width: 100px;
height: 100px;
background-color: orange;
/*overflow: hidden;*/
/*display: inline-block;*/
/*float: left;*/
/*position: absolute;*/
}
几种方法中用哪一个比较好?首选float方法。
第二个Bug:margin合并。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="style1211.css">
</head>
<body>
<div class="up">up</div>
<div class="down">down</div>
</body>
</html>
*{
margin: 0;
padding: 0;
}
.up{
height: 40px;
background-color: red;
margin-bottom: 100px;
}
.down{
/*margin-top: 50px;*//*增加此行代码发现上下间距并没有增加*/
height: 40px;
background-color: yellow;
}
可以看到增加的代码并没有增加上下两个元素的间距,而是公用了一段距离。
怎么解决这个Bug?
方法一:(不建议使用,不要因为改Bug增加结构。但是能解决问题)在HTML结构中给up或者down增加父级结构并触发BFC。
<div class="wrapper">
<div class="up">up</div>
</div>
<div class="down">down</div>
.wrapper{
overflow: hidden;
}
方法二:不解决此问题。
上下两个兄弟元素垂直间距设置在一个属性(margin-bottom)下,为什么还要分开设置呢?比如上下两个元素间距100px,
设置上一个元素margin-bottom:100px即可,没有必要还要margin-bottom50px, margin-top50px 分开设置,虽然有Bug但能用数学
方法解决,开发过程能接受。