[CSS] Overflow清除Float效果的妙用
2011-02-19 by audi_lu 1 Comment
在使用css设计版面时我们常常会遇到的情况之一,就是用来包覆float子区块的父区块无法跟随float子区块的高度一并延伸:
float的子区块1
float的子区块2
而通常我们要解决这种情况,我们会增加一个具有 clear 属性的元素 (例:具有clear:both设定的div元素) 在float子区块后面来清除Float效果,让父区块可以成功的包覆子区块:
float的子区块1
float的子区块2
但是你知道吗?其实我们也可以用overflow这个属性来达到清除float的效果。什么是overflow呢,overflow属性原本是用来控制当内容超出显示范围时,是否出现卷轴效果的属性,它的预设值是visible,也就是让内容完全显示出来,不嵌入显示卷轴的显示区域。我们在此要使用的是设定是overflow:auto,也就是为内容嵌入显示卷轴的显示区域,但视情况显示卷轴。(请google以获得更多overflow的详细使用方式)
当我们为父区块设定overflow:auto的属性后,我们就不需额外去clear掉float的效果了:
float的子区块1
float的子区块2
Overflow:auto还有另一项用法,常用在作回覆区域时的排版设计。先来看看我们常在图片元素设定float效果,造成的所谓「文绕图」效果:
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
通常我们在图片上设定float效果,但文字部份不设定任何效果,来达成文绕图的效果。若是我们在文字区块上设定 overflow:auto,文字就不会再绕图了:
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
这种设定造成文字会视图片的宽度来切齐显示区域,而这样的设计很常在回覆区域的设计上见到,即是把大头照放一边,留言文字切齐放另一边。
不过,单纯使用Overflow来消除float效果也有它的副作用,如果使用overflow:auto,但不小心内容太多爆出界了,卷轴就会出现。也许你会想用overflow:hidden,强制卷轴别出现,但超出的内容依旧会不见。例如在里面放了一大段没有空白(space)字符的内容 (文字不会断行显示);或者在里头放了太大张的图片。
要解决这样的问题,可以在文字内容区块设定 word-wrap: break-word,如此可以让文字内容自动断行显示;而针对太大张的图片,可以设定图片区块的 max-width:100%以及 height:auto,让它依照父区块的最大尺寸来延伸,而不会超出界。