浮动存在的意义
1.文本字环绕图片那样的容器
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<!-- 什么叫浮动 为了让文字与图片平行,为了减少从文字里扣空间放图片的场景,去实现文字环绕的场景-->
<style>
img {
float: left;
}
</style>
<body>
<div>
<img width="100" height="100" src="./u=3610006291,1844666164&fm=253&fmt=auto&app=120&f=JPEG.webp" alt="">
<p>okat Object..js (node:internal/modules/cjs/loader:1689:10)
at Module.load (node:internal/modules/cjs/loader:1318:32)
at Function._load (node:internal/modules/cjs/loader:1128:12)
at TracingChannel.traceSync (node:diagnostics_channel:315:14)
at wrapModuleLoad (node:internal/modules/cjs/loader:218:24)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:170:5)
at node:internal/main/run_main_module:36:49</p>
</div>
</body>
</html>
输出结果:
产生的原因
1.在文档流中,容器是从上往下,从左往右的布局排列,遵从标签的特性,不会有两个容器重叠
2.浮动会导致元素脱离文档流,但文字不会被盖住
浮动的负面影响
1.浮动的元素高度不计算在父容器的高度内,这就会导致父容器的后序容器布局和该浮动元素重叠 实例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
ul {
list-style: none;
margin: 0;
padding: 0;
/* 高度为零 */
}
li {
width: 200px;
height: 50px;
float: left;
}
li:nth-child(1) {
background-color: red;
}
li:nth-child(2) {
background-color: yellow;
}
li:nth-child(3) {
background-color: green;
}
.box {
width: 500px;
height: 100px;
background: purple;
}
</style>
</head>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<div class="box"></div>
</body>
</html>
-
清除浮动:
1.给父容器设置高度(缺点:在一些情况不能确定父容器的高度)
ul { list-style: none; margin: 0; padding: 0; height:100px; }2.在浮动元素最末尾增加一个子容器做清除浮动(clear:both;)
.box2 { clear:both; } <body> <ul> <li>1</li> <li>2</li> <li>3</li> <div class="box2"></div>/添加 </ul> <div class="box"></div>
3.添加伪元素(最好)
ul::after {
content: "hello";
clear: both;
display: block;
}
4.给后面被影响的元素添加清除浮动(clear:both;)(不太好,代码中谁的问题谁解决)
.box{
clear:both;
}
5.给父级元素添加 BFC
改后:
BFC ---Block Formatting Context
一个拥有隔离空间的容器 用来解决父子容器margin重叠的问题
创建 BFC 的方法
1.overflow:auto||hidden||overylay||scroll
2.position:absolute||fixed
3.display:inline-XXXX||flex||grid||table-XXXX
4.float:right||left
特征
1.bfc容器是让处于bfc内部的元素和外部的元素相互隔离,是外部元素的定位不会相互影响
2.解决外边距重叠问题
3.bfc容器在计算高度时,会将计算浮动的元素在内 原型 (Prototype)