圣杯和双飞翼布局都属于三栏布局,只不过是要求中间自适应盒子必须写在前边。

1. 圣杯布局

<div class="container">
    <div class="content"></div>
    <div class="left"></div>
    <div class="right"></div>
</div>

圣杯布局,利用浮动和负边距来实现。父级元素设置左右的 padding,三列均设置向左浮动,中间一列放在最前面,宽度设置为父级元素的宽度,因此后面两列都被挤到了下一行,通过设置 margin 负值将其移动到上一行,再利用相对定位,定位到两边。

.container{
    position: relative;
    padding-left: 100px;
    padding-right: 200px;
    height: 100px;
}
.content{
    float: left;
    width: 100%;
    height: 100px;
    background-color: blue;
}
.left{
    float: left;
    width: 100px;
    height: 100px;
    background-color: red;
    margin-left: -100%;
    position: relative;
    left: -100px;
}
.right{
    float: left;
    width: 200px;
    height: 100px;
    background-color: green;
    margin-left: -200px;
    position: relative;
    right: -200px;
}

2. 双飞翼布局

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

双飞翼布局相对于圣杯布局来说,左右位置的保留是通过中间列的 margin 值来实现的,而不是通过父元素的 padding 来实现的。本质上来说,也是通过浮动和外边距负值来实现的。

.container{
    width: 100%;
    height: 100px;
}
.wrap{
    float: left;
    width: 100%;
}
.center{
    background-color: blue;
    height: 100px;
    margin-left: 100px;
    margin-right: 200px;
}
.left{
    float: left;
    margin-left: -100%;
    width: 100px;
    height: 100px;
    background-color: red;
}
.right{
    float: left;
    margin-left: -200px;
    width: 200px;
    height: 100px;
    background-color: green;
}

3. flex实现

<div class="container">
    <div class="content"></div>
    <div class="left"></div>
    <div class="right"></div>
</div>
.container{
    display: flex;
    height: 100px;
}
.content{
    flex: 1 1;
    height: 100px;
    background-color: blue;
    order: 2;
}
.left{
    flex: 0 0 100px;
    height: 100px;
    background-color: red; 
    order: 1; 
}
.right{
    flex: 0 0 200px;
    height: 100px;
    background-color: green;
    order: 3;
}
文档更新时间: 2023-01-05 17:22   作者:孙老师