WEB前端 -- 浮动

来源:互联网 发布:java float与double 编辑:程序博客网 时间:2024/06/11 07:51

1.float:浮动

浮动的核心:浮动元素会脱离文档流并向左/向右浮动,直到碰到父元素或者另一个浮动元素。

<div class="div1"></div><div class="div2"></div><div class="div3"></div>
<style> div{ width:100px; height:50px;} .div1{ background:#3F0; float:left;} .div2{ background:#CF0; float:left} .div3{ background:#F96; width:200px; height:100px}</style>
div1、div2进行了左浮动float:left;,div1 、div2脱离了文档流,div1、div2会覆盖在div3上。

当浮动影响布局时,一般在有浮动的元素后面加一个宽、高都为0的空的div

<div class="div1"></div><div class="div2"></div><div class="clear"></div><div class="div3"></div>
<style> div{ width:100px; height:50px;} .div1{ background:#3F0; float:left;} .div2{ background:#CF0; float:left} .div3{ background:#F96; width:200px; height:100px} .clear{ clear:both; width:0px; height:0px;}</style>
2.清除浮动
影响整个布局需要清理浮动。清除浮动有3种方法:

1)在设置浮动的元素后面加一个宽、高均为0的空div

<div class="dClass">    <div class="box1">1</div>    <div class="box2">2</div>    <div class="box3">3</div>    <div class="clear"></div>    <div class="box4">4</div></div><style>    .dClass{ border:10px solid red; margin:0 auto; padding:100px;}    .box1{ width:200px; height:100px; background:#FC0;float:left;}    .box2{ width:200px; height:100px; background:#F90;float:left;}    .box3{ width:200px; height:100px; background:#FD0;float:left;}    .clear{ width:0; height:0; clear:both;}    .box4{ width:200px; height:100px; background:#FF0;float:left;}</style>

2)加伪元素

<div class="div1 clearfloat"> <div class="left">left左浮动</div> <div class="right">right右浮动</div> </div><div class="div2">   div2</div><style>   .left{float:left;width:20%;height:100px;background:#DDD}   .right{float:right;width:30%;height:50px;background:#DDD}   /*清除浮动代码*/   .clearfloat:after{content:"";clear:both; display:block;}   .clearfloat{zoom:1}</style>

注:zoom介绍

3)overflow:hidden;

<div class="div1Class"> <div class="left">left左浮动</div> <div class="right">right右浮动</div></div><div class="div2Class">   div2测试</div><style>
   /*第一种*/
   .div1Class{background:#F60;border:1px solid red;width:500px;overflow;hidden;}
/*第二种*/ /*.div1{background:#F60;border:1px solid red;zoom:1;overflow:hidden;}*/ .div2Class{background:#F90;border:1px solid red;height:100px;margin-top:20px;width:500px;} .left{float:left;width:200px;height:300px;background:#66C} .right{float:right;width:100px;height:100px;background:#66C}</style>

注:用overflow:hidden;时需要设置width或zoom,不用设置height,浏览器可以检查浮动区域的高度
4)设置高度

<div class="div1Class"> <div class="left">left左浮动</div> <div class="right">right右浮动</div></div><div class="div2Class">   div2测试</div><style>   .div1Class{background:#F60;border:1px solid red;width:500px;height:500px;}   .div2Class{background:#F90;border:1px solid red;height:100px;margin-top:20px;width:500px;}      .left{float:left;width:200px;height:300px;background:#66C}   .right{float:right;width:100px;height:100px;background:#66C}</style>