1、超出隐藏
<div class="a">
<div class="b">111</div>
<div class="b">222</div>
<div class="b">333</div>
</div>
.a{
width: 100px;
height: 100px;
overflow: hidden;
}
.b{
font-size: 30px;
}
运行结果:
可以看出333是没有显示完全的,这里是高度不够导致隐藏,宽度设置不够同理。(也能发现font-size的大小并不是整个div 的大小。)
2、清除浮动
当父级元素没有设置高度时,其子元素都浮动后,父元素无法检测其子元素的大小,因此导致父元素高度为0。
2.1这里父元素a有设置高度效果:
<body>
<div class="a">aaa
<div class="b">bbb</div>
<div class="c">ccc</div>
<div class="d">ddd</div>
</div>
</body>
.a{
width: 500px;
height: 500px;
background-color: blue;
}
.b{
width: 50px;
height: 50px;
background-color: red;
float: right;
}
.c{
width: 50px;
height: 50px;
background: gray;
float: right;
}
.d{
width: 50px;
height: 50px;
background:yellow;
float: right;
}
2.2这里父元素a没有设置高度效果:
.a{
background-color: blue;
}
运行效果: 其bcd都设置浮动后脱离父文档流,因此父a只能检测到自己aaa文字的大小。(如果父元素没有内容,则高度为0)
2.3这里父元素添加overflow: hidden;
.a{
background-color: blue;
overflow: hidden;
}
运行效果:
可以看到其父元素检测到了其子元素浮动后的高度
3、解决塌陷问题
当给子元素设置margin-top时,父元素没有内容时也会跟着整个页面一起下降。
<body>
<div class="a">
<div class="b">bbb</div>
</div>
</body>
.a{
width: 300px;
height: 200px;
background-color: blue;
/* overflow: hidden; */
}
.b{
width: 50px;
height: 100px;
background-color: red;
margin-top: 100px;
}
代码效果:
添加
.a{
width: 300px;
height: 200px;
background-color: blue;
overflow: hidden;
}
代码效果: