圣杯布局和双飞翼布局

94 阅读2分钟

圣杯布局和双飞翼布局都是实现三栏布局,左右两栏定宽,中间自适应,中间放在文档流前面并优先渲染。

区别在于代码的实现的方式不同,简单来讲:双飞翼布局比圣杯布局多创建了一个div,但是不用相对布局了。

圣杯布局:

原理:利用浮动,左中右处于浮动状态。容器利用padding-left,padding-right将左右块的预留的宽度定义出来。左右块通过设置magin-left的值为负数将自身和中间块在同一水平位置上。左右块再通过相对定位,移除容器到预留的位置上去。

/* css */
.container {
    padding-left: 150px;
    padding-right: 190px;
    height: 300px;
}
.main {
    float: left;
    width: 100%;
    background: #0ff;
    height: 100%;
}
.left {
    float: left;
    width: 150px;
    margin-left: -100%;
    position: relative;
    left: -150px;
    background: #f0f;
    height: 100%;
}
.right {
    float: left;
    width: 190px;
    margin-left: -190px;
    position: relative;
    right: -190px;
    background: #ff0;
    height: 100%;
}
<!-- html -->
<div class="container">
    <div class="main"></div>
    <div class="left"></div>
    <div class="right"></div>
</div>

双飞翼布局

左中右块都设置成浮动元素,在中间块中再添加一个元素,用来展示中间块内容,将元素设置margin-left,margin-right属性,预留出中间块的内容。左右块通过设置margin-left移动的设定的位置上去。

/* css */
.container {
    height: 300px;
}
.main-wrap {
    width: 100%;
    float: left;
}
.main {
    margin-left: 150px;
    margin-right: 190px;
    background: #0ff;
    height: 100%;
}
.left {
    float: left;
    width: 150px;
    margin-left: -100%;
    background: #f0f;
    height: 100%;
}
.right {
    float: left;
    width: 190px;
    margin-left: -190px;
    background: #ff0;
    height: 100%;
}
<!-- html -->
<div class="container">
    <div class="main-wrap">
        <div class="main"></div>
    </div>
    <div class="left"></div>
    <div class="right"></div>
</div>