浮动元素产生的浮动流及消除
2019-01-17 本文已影响0人
DARKSIIIDE
一、浮动元素会产生浮动流
HTML
<div class="box"></div>
<div class="demo"></div>
浮动元素产生浮动流
所有产生了浮动流的元素,只有块级元素看不到他们
产生了bfc的元素和文本类属性(带有inline属性)的元素以及文本都能看到浮动元素
CSS
.box{
float: left;
width: 100px;
height: 100px;
background-color: black;
}
.demo{
width: 150px;
height: 150px;
background-color: green;
}


二、消除浮动流
例如
HTML
<div class="wrapper">
<div class="content">1</div>
<div class="content">2</div>
<div class="content">3</div>
</div>
CSS
.wrapper{
border: 1px solid black;
}
.content{
float: left;
color: #fff;
background-color: black;
width: 100px;
height: 100px;
}

1. plan1
给div中添加<p>标签
clear:both;属性消除浮动流
HTML
<div class="wrapper">
<div class="content">1</div>
<div class="content">2</div>
<div class="content">3</div>
<p></p>
</div>
CSS
p{
border-top: 0 solid green;
clear: both;
}


2. plan2 利用<div class="wrapper">标签的伪元素
CSS
.wrapper::after{
content: "";
clear: both;
display: block;
}
3. plan3 触发bfc
CSS
.wrapper{
position: absolute;
border: 2px solid red;
}
.content{
float: left;
color: #fff;
background-color: black;
width: 100px;
height: 100px;
}

凡是设置了position:absolute;/float:left/right;
会从系统内部把元素转换成inline-block所以会出现这个效果
例如
HTML
<span>123</span>
CSS
span{
background-color: red;
width: 100px;
height: 100px;
}
span是行级标签所以设置宽高无效

span{
position: absolute;
background-color: red;
width: 100px;
height: 100px;
}
span设置position:absolute;后变成行级块元素设置了宽高有效
