浮动的7大特性
- 浮动的元素会脱离标准流
<style>
* {
margin: 0;
padding: 0;
}
.box1 {
width: 500px;
margin: 100px auto;
border: 10px solid red;
}
.box2 {
/* float: left; */
width: 500px;
height: 300px;
background-color: wheat;
}
</style>
<body>
<div class="box1">
<div class="box2"></div>
</div>
</body>
若没有给.box2设置浮动,运行结果为下图所示:

但是若给.box2设置浮动后,结果如下图所示

由上述例子可以看出,元素设置浮动后会脱离标准流
- 浮动的元素会一行显示,并且元素顶部对齐
<style>
.box1 {
float: left;
width: 200px;
height: 100px;
background-color: wheat;
}
.box2 {
float: left;
width: 200px;
height: 200px;
background-color: pink;
}
.box3 {
float: left;
width: 300px;
height: 300px;
background-color: red;
}
.box4 {
float: left;
width: 400px;
height: 500px;
background-color: yellow;
}
</style>
<body>
<div class="box1">盒子1</div>
<div class="box2">盒子2</div>
<div class="box3">盒子3</div>
<div class="box4">盒子4</div>
</body>

-
任何类型的元素都可以设置浮动,浮动后具有行内块元素的特点
-
浮动的盒子不再保留原来的位置
.box1 {
/* float: left; */
width: 200px;
height: 200px;
background-color: yellowgreen;
}
.box2 {
width: 300px;
height: 300px;
background-color: violet;
}
<div class="box1"></div>
<div class="box2"></div>
在没有给.box1元素设置浮动之前,运行结果是.box1在.box2上显示,两个盒子各自独占一行,但是给.box1设置浮动之后,运行结果如下:

可以看到.box1设置浮动后原来的位置不再保留,.box元素涌上来了
- 若给行内元素设置了浮动,则可以直接给其设置宽高
- 块级元素如没有设置宽高,默认会和父级一样宽,但是添加浮动后,大小由内容撑开
- 浮动的元素不会压住标准流的文字,给元素浮动后,文本元素会围绕着浮动元素,而不是被浮动元素覆盖(文字围绕浮动元素)

本文详细解读了浮动元素在网页布局中的关键特性,包括脱离标准流、行内显示与对齐、元素位置变化、宽度自适应、文本环绕、元素类型适用性及标准流影响。通过实例演示,帮助理解浮动在前端设计中的核心作用。
2004

被折叠的 条评论
为什么被折叠?



