浮动&清除浮动

1.什么是浮动?
浮动就是让块级标签不独占一行。目的(使用场景):把块级标签元素可以排在一行上。
2.浮动的原理:
就是让元素脱离文档流,不占用标准流。
3.float的属性值:
left/right/none(默认,不浮动)
4.浮动后,后面的元素不管是块级元素还是行级元素 ,都不会显示在下一行
5.清除浮动:
目的:让后面的元素自动掉到下一行。
方法:
1)添加空标签,并设置样式:
clear:left;清除左浮动
clear:right;清除右浮动
clear:both;清除左 右浮动
clear:none;左右浮动 都不清除
2)要在清除浮动的父级添加样式:overflow:hidden;
overflow:hidden;超出部分隐藏,也可以用来清除浮动(在实际开发项目中首选)
3)要在清除浮动的元素的父级添加伪元素,并设定样式
:after {
contents:"";
display:block;
clear:both;
}
具体实现
html:

<div class="wrapper">
    <div class="box1">box1</div>
    <div class="box2">box2</div>
    <div class="box3">box3</div>
</div>

css:

.wrapper { width: 600px;margin: 0 auto;border: 1px solid #666;}
.box1,.box2 { width: 100px;height: 100px;float: left;}
.box1 { background-color: red;float: left;}
.box2 { background-color: #282eff;float: right;}
.box3 { width: 100px;height: 100px;background-color: #45ff2d;}
image.png

方法一
html:

<div class="wrapper">
    <div class="box1">box1</div>
    <div class="box2">box2</div>
    <!--清除浮动方法1:添加空标签-->
    <div class="clear"></div>
    <div class="box3">box3</div>
</div>

css:

.clear { clear: both;}

方法二
html:

<!--清除浮动方法2:父级添加overflow:hidden-->
<div class="wrapper">
    <div class="box1">box1</div>
    <div class="box2">box2</div>
</div>
<div class="box3">box3</div><!--此时box3不能在wrapper内部,不然会被当做超出部分隐藏的-->

css:

 .wrapper { width: 600px;margin: 0 auto;border: 1px solid #666;overflow: hidden;}

方法三
html:

<!--清除浮动方法3:父级添加伪元素::after{content"";display:block;clear:both}-->
<div class="wrapper">
    <div class="box1">box1</div>
    <div class="box2">box2</div>
</div>
<div class="box3">box3</div>

css:

 .wrapper:after {content: "";display: block;clear: both;}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。