高度塌陷的最终解决方案
一、使用 clear 解决
1.clear 简介:
给一块元素设置 clear 属性后,将消除它上面元素因浮动对它造成的影响。(可选值:left,right,both)
For example:
<style>
.box1{
width: 200px;
height: 200px;
background-color: #bfa;
float: left;
}
.box2{
width: 200px;
height: 200px;
background-color: aqua;
clear: both;
}
</style>
</head>
<body>
<div class="box1">1</div>
<div class="box2">2</div>
</body>
此时,box2 因为有了clear 的 “净化” Buff,从而不会跑到 box1 正下方(看不见了),而是像 box1 没有浮动一样,呆在box1 底部。
2. 那如何使用 clear 的神奇特性来解决高度塌陷呢:
so easy,此时只要再在box1内创建一个 box3,使用 clear 消除box2 浮动的影响就好啦:
<style>
.box1{
border: red 10px solid;
}
.box2{
width: 100px;
height: 100px;
background-color: #bfa;
float: left;
.box3{
clear: left;
}
</style>
</head>
<body>
<div class="box1">
<div class="box2"></div>
<div class="box3"></div>
</div>
3. 对此方案的评价:
我们知道,html 解决结构,CSS解决样式,而我们添加了一个 div 标签,仅仅来解决表现的问题,应该不太合适吧。所以,有没有另一种方法,仅用CSS就可以解决呢?答案即为下面的方案。
二 、使用 after 伪类解决
根据方案一,我们应该找一个东西,它在 box1 的最后面,且能撑起box1,那除了设置 box3,我们还有另一种方式:after 伪类:
<style>
.box1{
border: red 10px solid;
}
.box2{
width: 100px;
height: 100px;
background-color: #bfa;
float: left;
}
.box1::after{ 注意:这里需要将其设置为 block,才能使用 clear
display: block;
content: ' ' ;
clear: left;
}
</style>
</head>
<body>
<div class="box1">
<div class="box2"></div>
</div>
总结:两种方案其实都可以达到目的,根据个人喜好选一种咯 ~
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?