CSS中浮动属性(float)设计的初衷是为了解决页面展现样式时须要文字环绕图片的场景;相似于Word中的文字环绕属性,基础使用场景以下:css
<style>
img{
float:left;
}
</style>
<div>
<img src="xxx.jpg" alt="test">
<p>xxx</p>
</div>
复制代码
因为设置了float后元素脱离了标准流,从而致使了高度的塌陷,这里有一个很直观的例子bash
当出现高度塌陷后本来想放在下面的元素会自动向上补充,出现这种结果布局
演示代码学习
<style type="text/css">
.div1{
height:100px;
width:100px;
background:blue;
float:left;
}
.div2{
height:10px;
width:300px;
background:red;
}
</style>
<main>
<div class="div1"></div>
<p>这里是一个段落</p>
</main>
<div class="div2"></div>
复制代码
清除浮动主流方法有两种:1)使用clear属性清除浮动;2)新建BFCui
方式一:在设置float的兄弟元素最后设置一个元素,对其设置clear属性,以下spa
<style type="text/css">
.div1{
height:100px;
width:100px;
background:blue;
float:left;
}
.div2{
height:10px;
width:300px;
background:red;
}
.clearfix{
clear:both;
}
</style>
<main>
<div class="div1"></div>
<p>这里是一个段落</p>
<table class="clearfix"></table>
</main>
<div class="div2"></div>
复制代码
方式二: 方式一的缺点仍是很明显的,就是无缘无故的新增了一个没有内容的元素,使页面出现冗余;这里能够利用伪元素来达到一样的效果设计
main::after{
content:"";
display:table;
clear:both;
}
复制代码
该方法的原理是:父元素在新建一个 BFC 时,其高度计算时会把浮动子元素的包进来。那么如何新建一个BFC呢3d
根元素或其它包含它的元素 浮动 (元素的 float 不是 none) 绝对定位的元素 (元素具备 position 为 absolute 或 fixed) 内联块 inline-blocks (元素具备 display: inline-block) 表格单元格 (元素具备 display: table-cell,HTML表格单元格默认属性) 表格标题 (元素具备 display: table-caption, HTML表格标题默认属性) 块元素具备overflow ,且值不是 visible display: flow-root 虽然有这么多方法可用,可咱们经常使用的就是 overflow: hiddencode
main{
overflow:hidden;
}
复制代码
也能够达到清除浮动的效果cdn
float元素设计的初衷虽然是文字环绕图片,可是目前其最普遍的应用倒是在布局领域,下面除了介绍如何应用在布局外,还会介绍几种常见的float布局方式,下面给出了最简单的流式布局样式
每一个div默认占据一行,不论宽度都会占满此行;float布局的核心思想就是怎么把这些一行一行的数据给他以美观的方式呈现出来
代码演示
<div class="div1" style="background-color:red;height:100px;width:350px">
div1
</div>
<div class="div2" style="background-color:blue;height:120px;width:200px">
div2
</div>
<div class="div3" style="background-color:green;height:140px;width:50px">
div3
</div>
<div class="div4" style="background-color:yellow;height:100px;width:600px">
div4
</div>
复制代码
为何会出现这种状况呢?div3莫名其妙的变短了? 其实并非div3变短了,而是div2设置浮动后脱离了页面的流,悬浮在了其余元素的上面,而div2脱离后div3天然的向上补充,带着div4总体上移,又被div2挡住了一部分因此出现了上图中的状况,对比看一下div2右浮动就比较清晰了
同理,这里div2 div3脱离标准流并悬浮其上,组成了一个新的层次;div4直接上移,部分被di2和div3所遮挡
代码示例(为了美观作了部分调整,关注重点便可)
<style>
.div1,.div2,.div3{
float:left;
margin:0 10px;
}
.div4{margin:10 10px;}
.clear-fix::after {
content: "";
display: table;
clear: both;
}
</style>
<main class="clear-fix">
<div class="div2" style="background-color:blue;height:120px;width:100px;">
div2
</div>
<div class="div1" style="background-color:red;height:100px;width:350px;">
div1
</div>
<div class="div3" style="background-color:green;height:140px;width:50px;">
div3
</div>
</main>
<div class="div4" style="background-color:yellow;height:30px;width:540px">
div4
</div>
复制代码
最终样式以下,是网页中很是常见的三列布局方式
这里介绍了CSS浮动的基本知识,因为篇幅缘由有些比较基础细致的知识没有包含,你们感兴趣能够本身学习下!
下面一篇博客会有具体的例子供你们参考,有须要的能够看下