一个关于float元素的布局

面试,碰到一个css题,完成这样一个的效果,

在内部只有三个标签,并且顺序为红粉橙的情况下,怎么完成?

初步想法是左边两个小块float,右边给一个为非float的元素加一个margin-left值,

给出一个做法是:

<div style="width:200px; height:200px; background:#000; overflow:hidden;">
<div style="float:left; clear:right; width:50px; height:50px; background:#ff0000;"></div>
<div style="float:left;  width:50px; height:50px; background:#ff00ff;"></div>
<div style="height:200px; background:#ff6600; margin:0 0 0 50px;"></div>
</div>

当时不是上机,没有验证,回来测试,得到如下效果

完了,clear:right,对下一个float元素没有起作用,想到当时面试官给出的方案:

红粉色块为非float,橙为float加负margin:

<div style="width:200px; height:200px; background:#000; overflow:hidden;">
<div style="width:50px; height:50px; background:#ff0000;"></div>
<div style="width:50px; height:50px; background:#ff00ff;"></div>
<div style="float:left; width:100%; height:200px; background:#ff6600; margin:-100px 0 0 50px;"></div>
</div>

当然,得到了正确结果,但margin-top值需要设定一个定值,是不是有方案可以自动适应不同的左栏高度?

想想又回到了最初的思路,改了一下代码:

<div style="width:200px; height:200px; background:#000; overflow:hidden;">
<div style="float:left; width:50px; height:100px; background:#ff0000;"></div>
<div style="float:left; clear:left; width:50px; height:50px; background:#ff00ff;"></div>
<div style="height:200px; background:#ff6600; margin:0 0 0 50px;"></div>
</div>

得到预期效果,并且左栏各块高度的变化,不会影响右栏,

为什么clear:right不可以,而clear:left可以呢?

这个属性较少用,所以重新查看了一下定义,w3school上说:

其实它的这种说法很含糊,发现自己果然一直是不求甚解,理解不到位,参考一文章的说法:

clear:left,是针对前面元素带有float:left的元素有效,

clear:right,是针对前面元素带有float:right的元素有效,

实践一下,果然如此,并且,如果给float元素后的float元素设置clear的话,将使前面的float产生实际占位,

非float元素不会重叠到float元素下方。

 

顺便发现个以前没注意的(在inline-block后的float:left元素,在宽度能一行时,float:left元素在前,

而宽度不够折行时,则是float:left元素在后)

 

 

posted on 2014-11-24 15:27  流光易逝  阅读(1452)  评论(0编辑  收藏  举报

导航