CSS实现元素浮动和清除浮动的方法

2020-05-16 07:14:37易采站长站整理

width: 100px;
height: 100px;
background-color: #0f0;
}
.box3{
width: 100px;
height: 100px;
background-color: #00f;
}
</style>
</head>

<body>
<div class="box">
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
</div>
</body>
</html>

结果图

为什么会排列为3行呢,因为3个

div
标签都是块级元素。
现在我们将
class
属性值为
.box1
的元素设置为右浮动。

代码块


<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>浮动</title>
<style>
.box{
width: 600px;
border: 1px solid #000;
}
.box1{
width: 100px;
height: 100px;
background-color: #f00;
float:right;
}
.box2{
width: 100px;
height: 100px;
background-color: #0f0;
}
.box3{
width: 100px;
height: 100px;
background-color: #00f;
}
</style>
</head>

<body>
<div class="box">
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
</div>
</body>
</html>

结果图

注意:现在我们发现

calss
属性值为
.box
元素高度变矮了,这就说明了(浮动元素它已经脱离了标准文档流,不再占用空间了)、并且向右浮动,浮动到自身的父元素的边缘位置就停止了浮动。

左浮动实践

让我们进入左浮动的实践,实践内容如:将

class
属性值为
.box1
元素设置为左浮动。

代码块


<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">