clear的理解

来源:互联网 发布:辛普森悖论 知乎 编辑:程序博客网 时间:2024/06/05 02:01

之前对于clear,很少用。

以前对divfloat之后,影响了其他元素,所以我设计的所有web页面,第一定义就是float。这样所有页面的元素都是脱离文档流来定位的,虽然天下乌鸦一般黑,——但是总是感觉比较另类,不那么高级。


于是今天看到一个clear:这个只是会影响自己dom元素,不会影响其他元素。

增加clear之后,页面在渲染本dom的时候,按照文档流,进行位置判断,如果发现将要依附的元素有float属性,则避而远之,继续在判断下一个,一直找到最后一float,然后换一行,安顿下来。(clear:与 float  不共戴天,但clear弱势,不能左右别人,只能避而远之,但是又不会离太远,就是紧接着下一行

比如 :按照加载顺序,浏览器这样判断

div1 :脱离文档流按照左浮动

div2:发现div1并没有占用位置,就默认顶到了第一个——其实就藏到了div1的背后

div3:按照文档流,先判断2的位置,然后基于标准的文档流,然后在相对于2的位置,换一行进行float

div4:会找上一个元素,发现是div3,是一个带float,赶快躲开 于是紧接着div3安顿下来了。

<style type="text/css">    #test div{        border:1px solid #000;        /*position: relative;*//*        top:5px;        left:5px;*/        /*float:left;*/    }</style><div style="width:1200px; border:1px solid #f60" id="test">    <div style="width:200px;height:100px;border:1px solid blue;float:left">1</div>    <div style="width:200px;height:150px;border:1px solid red;">2</div>    <div style="width:200px;height:150px;border:1px solid green;float:left">3</div>    <div style="width:300px;clear:left">clear</div></div>

类似于这种




还有一个例子

<style type="text/css">    #test div{        border:1px solid #000;        /*position: relative;*//*        top:5px;        left:5px;*/        /*float:left;*/    }</style><div style="width:1200px; border:1px solid #f60" id="test">    <div style="width:200px;height:200px;border:1px solid blue;float:left">1</div>    <div style="width:200px;height:150px;border:1px solid red;;float:left">2</div>    <div style="width:300px;clear:left">clear</div>    <div style="width:200px;height:150px;border:1px solid green;">3</div></div>
效果:


参考这里:http://www.zhangxinxu.com/wordpress/2014/06/understand-css-clear-left-right-and-use/

0 0
原创粉丝点击