我们一般讨论的自适应高度的DIV布局,都是指有背景区分的,但在我们的实际应用中,很少有网站这么用的,大多数都不是用背景区分的。但今天我们并 不是讨论它的实用性如何,而只讨论实现这种布局的一种较完美的解决方法。
顾名思义,所谓的自适应高度,就是某一列撑长而其它列的高度也跟随相应地被撑长,这个效果如果用table的话,轻而易举就完成了,而用DIV就没 这么容易了。之前也有试过不少的方法,比如用JS控制、padding-bottom 给个很大的负值……但都觉得不太理想。后来在一个国外的网站上看到一个,感觉这是目前为止比较满意的解决方法了,不用hack、不用JS、兼容性强……
原理很容易,理解之后应该可以解决很多这样的布局方案了。见上图,.colmask、.colmin、.colleft,分别为三列背景的容器,最 外层的 .colmask 设定 overflow:hidden;,通过相对定位分成三列。而内容容器 .col1、 .col2、 .col3 都放在最内层的 .colleft 里面,通过相对定位定好位置,所以不管 .col1、 .col2、 .col3 哪一个伸长或缩短,外部的 .colmask、.colmin、.colleft 都会跟着伸长与缩短,也就实现了我们所要的效果了。
看看演示效果:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>完美的DIV三行三列自适应高度布局</title> <style type="text/css"> body { margin:0; padding:0; font-size:12px; } .header { width:100%; height:50px; background:#EEE; border-bottom:1px solid #000; } .colmask { position:relative; clear:both; width:100%; overflow:hidden; } .colright, .colmid, .colleft { float:left; width:100%; position:relative; } .col1, .col2, .col3 { float:left; position:relative; overflow:hidden; } .threecol { background:#BBB; } .threecol .colmid { right:20%; background:#CCC; } .threecol .colleft { right:60%; background:#DDD; } .threecol .col1 { width:58%; left:101%; } .threecol .col2 { width:18%; left:23%; } .threecol .col3 { width:18%; left:85%; } .footer { clear:both; width:100%; height:50px; background:#EEE; border-top:1px solid #000; } </style> </head> <body> <div class="header"> 这里是头部 </div> <div class="colmask threecol"> <div class="colmid"> <div class="colleft"> <div class="col1"> <p>这里是中间</p> <p>这里是中间</p> <p>这里是中间</p> <p>这里是中间</p> <p>这里是中间</p> <p>这里是中间</p> <p>这里是中间</p> <p>这里是中间</p> <p>这里是中间</p> <p>这里是中间</p> <p>这里是中间</p> <p>这里是中间</p> <p>这里是中间</p> </div> <div class="col2"> 这里是左栏 </div> <div class="col3"> <p>这里是右栏</p> <p>这里是右栏</p> <p>这里是右栏</p> <p>这里是右栏</p> </div> </div> </div> </div> <div class="footer"> 这里是底部 </div> </body> </html> |
|