学习浮动,首先了解DOM流(普通流)
DOM流(普通流)定义:
除非专门指定,否则所有框都在普通流中定位。也就是说,普通流中的元素的位置由元素在 (X)HTML中的位置决定。
DOM流中块级元素即使给定宽度,同级的元素依旧会另起一行。以3个div盒子为例。
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Title</title>
<!-- 外部样式表 -->
<link rel="stylesheet" href="css/css-index.css">
</head>
<body>
<div class="box">
box1
</div>
<div class="box">
box2
</div>
<div class="box">
box3
</div>
</body>
</html>
css-index.css
.box{
width:300px;
height:200px;
max-height: 400px;
background-color: blueviolet;
color: white;
font-size: 32px;
}
在浏览器中显示
在实际运用中,很多时候我们需要将多个box在同一行排列,这时候就要用到浮动
浮动定义:
浮动的框可以向左或向右移动,直到它的外边缘碰到包含框或另一个浮动框的边框为止。浮动框脱离DOM流,父级元素会表现的浮动框不存在一样。
港真如果只看定义的话,还挺难懂的T-T
简单示例
`css-index.css
.box{
width:300px;
height:200px;
max-height: 400px;
background-color: blueviolet;
color: white;
font-size: 32px;
/* 向左浮动,使得三个box横向排列 */
float:left;
}
浮动后浏览器显示
可以看出浮动取消了DOM流的格式,使得三个box在一行中排列。
然而这样的写法会带来一些预料之外的后果,假设给box加一个父级元素father。
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Title</title>
<!-- 外部样式表 -->
<link rel="stylesheet" href="css/css-index.css">
</head>
<body>
<div class="father">
<div class="box">
box1
</div>
<div class="box">
box2
</div>
<div class="box">
box3
</div>
</div>
</body>
</html>
在css中添加
.father{
background-color: yellow;
}
然而在浏览器显示中并没有出现黄色背景,原因就是浮动后系统会默认父级元素中没有任何元素,从而使得父级元素高度变为0。
为了后续元素不受浮动带来的副作用的影响,这里就需要使用清除浮动
在css中添加一个公共类clear来清除浮动
定义:
clear 属性规定元素的哪一侧不允许其他浮动元素。
浮动和清除浮动成对出现
清除浮动一般放在最靠近浮动元素的尾部,清除浮动只对同级元素有效
检查是否正确清除浮动,看父级元素的高度,高度==0,浮动没清除
.clear{
clear:both;
/* 最常用属性值both,使得元素两侧都不能有浮动元素 */
}
在父级元素father中添加clear类
<div class="father">
<div class="box">
box1
</div>
<div class="box">
box2
</div>
<div class="box">
box3
</div>
<!-- 清除浮动一般放在最靠近浮动元素的尾部,清除浮动只对同级元素有效 -->
<!-- 将父级元素高度还原 -->
<div class="clear"></div>
</div>
还原father高度后刷新浏览器页面显示
到此为止,后续元素继续写就不会受到浮动的影响了嗷O-o