CSS浮动(Float)是一种布局技术,它允许元素脱离正常的文档流,向左或向右浮动,直到遇到父容器的边缘或者另一个浮动元素为止。浮动最初是为了实现文本环绕图片的效果而设计的,但现在它也被广泛用于更复杂的布局设计。
float
)的元素。left
:元素向左浮动。right
:元素向右浮动。none
:元素不浮动(默认值)。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Float Example</title>
<style>
.container {
width: 400px;
border: 1px solid black;
}
.float-left {
float: left;
width: 100px;
height: 100px;
background-color: red;
}
.float-right {
float: right;
width: 100px;
height: 100px;
background-color: blue;
}
.clear {
clear: both;
}
</style>
</head>
<body>
<div class="container">
<div class="float-left"></div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
<div class="float-right"></div>
<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
<div class="clear"></div>
<p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</p>
</div>
</body>
</html>
原因:浮动元素脱离了正常的文档流,不再撑开父容器的高度,导致父容器高度塌陷。
解决方法:
overflow: hidden/auto
:.container {
overflow: hidden;
}
clear: both
:<div class="clear"></div>
.clear {
clear: both;
}
.container::after {
content: "";
display: table;
clear: both;
}
通过以上信息,你应该能够理解CSS浮动的基础概念、优势、类型、应用场景以及常见问题的解决方法。
领取专属 10元无门槛券
手把手带您无忧上云