CSS浮动
本文主要介绍float元素的一些简单使用。
float可以使元素向左或向右浮动,当元素被float时,会变成一个块盒(block)。
1.语法
float的属性值:
- left:左浮动,使元素靠上靠左
- right:右浮动,使元素靠上靠右
- 默认值:none
2.举例
以下将通过几个简单的例子,来说明float的使用方式。
- 让元素浮动
这是一个没有浮动效果的结果图,一个红色的大div包裹三个颜色不同的的div。接下来让div浮动。
当让蓝色div向左浮动起来我们可以看到这样的一个结果,绿色div无视了浮动的蓝色div的位置,直接被蓝色div给遮挡了。说明在使用浮动要注意常规流盒子的位置,不要被浮动盒子遮住了。
那么按照这样的规则,当蓝色div向右浮动时,是不是左边有两个div,右边有一个div。代码如下感兴趣的可以运行试一下。
<!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>
.demo{
width: 500px;
height: 500px;
background-color: red;
}
.first{
width: 200px;
height: 200px;
background-color: blue;
float: right;
}
.two{
width: 210px;
height: 200px;
background-color: green;
}
.three{
width: 200px;
height: 200px;
background-color: orange;
}
</style>
</head>
<body>
<div class="demo">
<div class="first">
我是第一个
</div>
<div class="two">
我是第二个
</div>
<div class="three">
我是第三个
</div>
</div>
</body>
</html>
结果如下:
- 当三个小div都向左浮动会得到这样的一个结果
为什么只有两个在一行,而第三个div在第二行呢?是不是因为长度问题呢,要知道红色div的长度为500px,而三个小div的总长度为:610px。打开F12,调一下第三个div的长度他会发生什么变化。
当第三个div的长度为90px时,三个div并列。说明浮动元素浮动的范围与父元素盒子的大小有很大的关系。当使用浮动时,可以通过调节父元素或是浮动元素的大小,来达到一些简单的布局。
代码如下,感兴趣的可以试一下。
<!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>
.demo{
width: 500px;
height: 500px;
background-color: red;
}
.first{
width: 200px;
height: 200px;
background-color: blue;
float: left;
}
.two{
width: 210px;
height: 200px;
background-color: green;
float: left;
}
.three{
width: 200px;
height: 200px;
background-color: orange;
float: left;
}
</style>
</head>
<body>
<div class="demo">
<div class="first">
我是第一个
</div>
<div class="two">
我是第二个
</div>
<div class="three">
我是第三个
</div>
</div>
</body>
</html>