您的位置:首页 > 其它

完美的DIV三行三列自适应高度布局

2009-09-09 11:49 405 查看
我们一般拿出来讨论的自适应高度的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>demo</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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: