首页 > 代码库 > css中的clear:both,display:flex;

css中的clear:both,display:flex;

   介绍两者一起讨论的原因:

在明天就国庆的日子里陪着程序员的只有代码,啤酒,还有音乐,然后就是灯光下默默陪伴自己的影子。好了,不矫情了。

-----------------------------------------------------------

先上两张图,然后慢慢道来......

技术分享

   技术分享

第一张是实现的布局,第二张是布局的代码。简单的说明一下:图一中有4块为classname为newsItem的div容器(代码有点乱看起来有点吃力),这4个容器包含在classname为newsRow的section中。每个newsItem容器里面又分了calssname的newsItem_left和newsItem_right的2个容器,分别代表每个newsItem容器的左和右的部分。然后定位如第一张图的样式!!

可能你会说这不简单,newsItem的display属性设置成inline-block。然后设置其width,margin属性,接着就是设置left和right样式,就可以设置成上面的样子了!但是,我在left和right的div里面是用flex布局,导致其父元素newsItem容器不得设置为display:flex;接着使用float;于是4个newsItem容器脱离了文档流,导致newsRow的section的容器,没有了高度;于是要清除浮动了;于是想一起讨论清除浮动和flex布局。

清除浮动的几种方法

     1,使用空标签清除浮动。

     2,使用overflow属性。

     3,使用after伪对象清除浮动。

     4,浮动外部元素。

    

这里就不上我那个复杂css的代码了,借鉴一下网上代码!

 第一种方法的代码:

<style type=”text/css”>*{margin:0;padding:0;}body{font:36px bold; color:#F00; text-align:center;}#layout{background:#FF9;}#left{float:left;width:20%;height:200px;background:#DDD;line-height:200px;}#right{float:right;width:30%;height:80px;background:#DDD;line-height:80px;}.clear{clear:both;}</style><body><div id=”layout”><div id=”left”>Left</div><div id=”right”>Right</div><div class=”clear”></div></div></body>

说明:在left,right同级里面加一个div空标签(可以是其他标签,如p,br),给其设置clear:both属性。

第二种方法的代码:

<style type=”text/css”>*{margin:0;padding:0;}body{font:36px bold; color:#F00; text-align:center;}#layout{background:#FF9;overflow:auto;zoom:1; } /* overflow:auto可以换成overflow:hidden,zoom:1可以换成width:100%*/#left{float:left;width:20%;height:200px;background:#DDD;line-height:200px;}#right{float:right;width:30%;height:80px;background:#DDD;line-height:80px;}</style><body><<div id=”layout”><div id=”left”>Left</div><div id=”right”>Right</div></div></body>

说明:给父元素添加一个overflow:auto也可以换成overflow:hidden,为了兼容万恶的ie6添加zoom:1也可以换成width:100%;

第三种方法的代码

 

<style type=”text/css”>*{margin:0;padding:0;}body{font:36px bold; color:#F00; text-align:center;}#layout{background:#FF9;}#layout:after{display:block;clear:both;content:””;visibility:hidden;height:0;}#left{float:left;width:20%;height:200px;background:#DDD;line-height:200px;}#right{float:right;width:30%;height:80px;background:#DDD;line-height:80px;}</style><body><<div id=”layout”><div id=”left”>Left</div><div id=”right”>Right</div></div></body>

 

说明:一、该方法中必须为需要清除浮动元素的伪对象中设置height:0,否则该元素会比实际高出若干像 素;二、content属性是必须的,但其值可以为空。

 

flex的布局

 

css中的clear:both,display:flex;