CSS实现中间自适应的三栏布局,共4种方法

来源:互联网 发布:百知尚行科技有限公司 编辑:程序博客网 时间:2024/05/16 12:08

一、float实现

html结构:

<div class="left"></div><div class="right"></div><div class="center"></div>
css:

.left,.right{width: 200px;height: 300px;background-color: red;}.left{float: left;}.right{float: right;}.center{margin: 0 210px;height: 300px;background-color: blue;}
这种实现受外界影响小,但是对html结构有要求(center必须放在最后,left与right则无所谓),当界面缩小到一定程度时,right会被挤到下一行


二、position实现

html结构:

<div class="left"></div><div class="right"></div><div class="center"></div>

css:

.left,.right{position: absolute;width: 200px;height: 300px;background-color: yellow;}.left{left: 0;}.right{right: 0;}.center{margin: 0 210px;height: 300px;background-color: blue;}
该法布局的好处,三个div顺序可以任意改变。不足是 因为绝对定位,所以如果页面上还有其他内容,top的值需要小心处理,最好能够对css样式进行一个初始化,如果不对样式进行初始化,则两边和中间的值会对不齐。 另外,随着浏览器窗口缩小,小于200px的时候,会发生重叠。摘自:http://blog.csdn.net/cinderella_hou/article/details/52156333


三、双飞翼布局

双飞翼布局与圣杯布局很像,关于二者差异,知乎上说的还蛮清楚的:CSS布局中圣杯布局与双飞翼布局的实现思路差异在哪里?

html结构:

<div class="center-wrapper"><div class="center">center</div></div><div class="left">left</div><div class="right">right</div>
css:

.center-wrapper,.left,.right{float: left;}.center-wrapper{width: 100%;height: 300px;background: pink;}.left{width: 200px;height: 300px;margin-left: -100%;background-color: orange;}.right{width: 200px;height: 300px;margin-left: -200px;background-color: red;}.center{margin: 0 210px;height: 300px;background-color: blue;}
这种方式有点复杂,其实就是通过把center-wrapper、left、right设为向左浮动,再通过margin将left和right调整到一行的指定位置上,这时left和right会覆盖住center,再通过center的margin将自己缩到中间(同float、position实现中的center的margin)。

html结构固定,center必须放到最前面,且需要wrapper包裹。


四、弹性布局实现

html结构:

<div class="box"><div class="left">left</div><div class="center">center</div><div class="right">right</div></div>
css:

.box{display: flex;width: 100%;}.left,.right{flex: 200px 0 0;/*width: 200px;*/height: 300px;background-color: yellow;}.center{flex: 1;background-color: pink;}

这种方式看着要简练的多,需要了解弹性布局的推荐阮一峰博客Flex布局教程-语法篇




阅读全文
0 0