浮动元素会产生浮动流
所有产生了浮动流的元素,块级元素看不到它们 ,
但是产生了BFC的元素和文本类属性(inline)的元素以及文本都能看到浮动元素
注:并未脱离文档,只有块级元素看不到它.
一, BFC解决
<style type="text/css">
.box{
border: 2px solid black;
overflow: hidden;/*创建BFC*/
}
.box-1{
width: 100px;
height: 100px;
background: blue;
float: left;
}
</style>
</head>
<body>
<h3>注意:使用overflow,块级父元素还是独占一行</h3>
<div class="box">
<div class="box-1">子元素 float:left;</div>
<div class="box-1">子元素 float:left;</div>
</div>
</body>
<style type="text/css">
.box{
border: 2px solid black;
position: absolute;/*创建BFC*/
}
.box-1{
width: 100px;
height: 100px;
background: blue;
float: left;
}
</style>
</head>
<body>
<h3>注意:使用position和,块级父元素会贴身包裹子元素</h3>
<!--凡是设置了position:absolute;和float:left/right;的元素,
系统会从内部把元素转换成inline-block.-->
<div class="box">
<div class="box-1">子元素 float:left;</div>
<div class="box-1">子元素 float:left;</div>
</div>
二, 清除浮动解决
注意: clear必须放在块元素(block)里.
<style type="text/css">
.box{
border: 2px solid black;
}
.box-1{
width: 100px;
height: 100px;
background: blue;
float: left;
}
</style>
</head>
<body>
<div class="box">
<div class="box-1">子元素 float:left;</div>
<div class="box-1">子元素 float:left;</div>
<p style="clear: both"></p>
<!--可以在最后添加空元素,通过清除浮动实现
缺点:会破坏HTML文档的结构,不建议使用-->
</div>
</body>
<style type="text/css">
.box{
border: 2px solid black;
}
.box-1{
width: 100px;
height: 100px;
background: blue;
float: left;
}
.box::after{ /*伪元素 系统默认是inline*/
content:'';/*必不可少*/
display: block;/*因为clear只有在block元素中才有效果*/
clear: left;
}
</style>
</head>
<body>
<h3>通过伪元素实现</h3>
<div class="box">
<div class="box-1">子元素 float:left;</div>
<div class="box-1">子元素 float:left;</div>
</div>