CSS第一弹——如何清除浮动
提示:本人是自学前端的一枚小小程序媛,以下内容是自己总结的笔记,如有错误,欢迎大家批评指正!!!!
清除浮动
在清除浮动之前我们需要弄清楚一点,为什么要清除浮动?
原因就是在父元素包裹子元素的情况下,给子元素设置了浮动,但是我们不方便给父级设置高度,如果父级没有高度,子元素脱离文档流,就会产生浮动塌陷。导致了父元素高度为0,影响了下面其他的元素,这时候就需要清除浮动
<style>
.father{
width: 200px;
height: 200px;
background-color: rgb(55, 75, 75);
}
.son{
float: right;
width: 100px;
height: 100px;
background-color: rgb(134, 134, 99);
}
</style>
</head>
<body>
<div class="father">
我是爹
<div class="son">
我是儿子
</div>
</div>
</body>
这是给父元素和子元素都设置高度的样子,当父元素不方便给高度时(比如当我们浏览百度文库的页面时,每篇文章内容所占的长度是不可控的,也就是不能给父元素设置高度,我们希望的是子元素内容会撑开父元素),我们看到的是这样的,而且这种情况还会影响其他的元素
<style>
.father{
width: 200px;
background-color: rgb(55, 75, 75);
}
.son{
float: right;
width: 100px;
height: 100px;
background-color: rgb(134, 134, 99);
}
</style>
</head>
<body>
<div class="father">
我是爹
<div class="son">
我是儿子
</div>
</div>
</body>
清除浮动的方法
1.给父元素设置高度,这是简单粗暴的解决办法,但是基本不会用,因为我们不想给父元素固定高度,so这种方法pass掉
<style>
.father{
width: 200px;
height: 200px;
background-color: rgb(55, 75, 75);
}
.son{
float: right;
width: 100px;
height: 100px;
background-color: rgb(134, 134, 99);
}
</style>
</head>
<body>
<div class="father">
我是爹
<div class="son">
我是儿子
</div>
</div>
</body>
2.在父元素里面的最末尾添加块级元素(空元素),给块级元素设置属性clear:both,这样清除浮动的好处是代码量少,但是添加了无语义标签,破坏了html的结构,后期不容易维护
<style>
.father{
width: 200px;
background-color: rgb(55, 75, 75);
}
.son{
float: right;
width: 100px;
height: 100px;
background-color: rgb(134, 134, 99);
}
.box{
clear: both;
}
</style>
</head>
<body>
<div class="father">
我是爹
<div class="son">
我是儿子
</div>
<div class="box"></div>
</div>
</body>
3.触发父元素的BFC,比如给父元素设置overflow:hidden/auto,display:inline-block等。(这里所说的BFC我们下篇文章会讲解)
<style>
.father{
width: 200px;
background-color: rgb(55, 75, 75);
overflow: hidden;
/* display: inline-block; */
}
.son{
float: right;
width: 100px;
height: 100px;
background-color: rgb(134, 134, 99);
}
</style>
</head>
<body>
<div class="father">
我是爹
<div class="son">
我是儿子
</div>
</div>
</body>
4.通过添加虚拟元素的方法来清除浮动,在父元素里的最末尾添加一个虚拟的块级元素,设置属性content为空,display为block,clear为both。他在实际开发中是最常用的,而且还可以兼容大部分浏览器,妥妥的一个赞
<style>
.father{
width: 200px;
background-color: rgb(55, 75, 75);
}
.father::after{
display: block;
content: '';
clear: both;
}
.son{
float: right;
width: 100px;
height: 100px;
background-color: rgb(134, 134, 99);
}
</style>
</head>
<body>
<div class="father">
我是爹
<div class="son">
我是儿子
</div>
</div>
</body>
以上就是关于清除浮动的分享!下期分享什么是BFC(块级格式化上下文)