圣杯布局与双飞翼布局的区别

2020-04-24  本文已影响0人  小本YuDL

目的:

圣杯布局和双飞翼布局解决的问题是相同的,就是两边顶宽,中间自适应的三栏布局,中间栏要在放在文档流前面以优先渲染。

区别:

实现:

圣杯布局和双飞翼布局解决问题的方案在前一半是相同的,也就是三栏全部float浮动,但左右两栏加上负margin让其跟中间栏div并排,以形成三栏布局。

1. 圣杯布局(position+float+padding)

      #left{
            float: left;
            position: relative;
            width: 200px;
            height: 100px;
            margin-left: -100%;
            background-color: red;
            left: -200px;
        }
        #right{
            float: left;
            position: relative;
            width: 200px;
            height: 100px;
            margin-left: -200px;
            background-color: #333333;
            right: -200px;
        }
        #center{
            float: left;
            width: 100%;
            height: 100px;
            background-color: #0086b3;
        }
        #content{
            padding: 0 200px 0 200px;
            height: 100px;
        }
<div id="content">
    <div id="center">middle</div>
    <div id="left">left</div>
    <div id="right">right</div>
</div>

2.双飞翼布局(float+margin)

        #center{
            float:left;
            width:100%;/*左栏上去到第一行*/
            height:100px;
            background:blue;
        }
        #left{
            float:left;
            width:180px;
            height:100px;
            margin-left:-100%;
            background: #f2d67f;
        }
        #right{
            float:left;
            width:200px;
            height:100px;
            margin-left:-200px;
            background: #ff3e31;
        }
       // 给内部div添加margin,把内容放到中间栏,其实整个背景还是100%
        #inside{
            margin:0 200px 0 180px;
            height:100%;
        }
<div id="center">
    <div id="inside">middle</div>
</div>
<div id="left">left</div>
<div id="right">right</div>

优缺点对比

结论

通过对比可看出,双飞翼布局比圣杯布局多创建了一个div,但是不用相对布局了。但是通过代码就可以看出双飞翼更加简洁。

细节解析

margin-left:-100%是什么意思?
意思就是向左移动整个屏幕的距离。
以双飞翼布局为例,将代码中所有的margin属性注释掉,我们会看到以下布局:

image.png
那下面将left 的margin设置为-100%,可以看下是什么效果:
设置之前解析

移动结果
上一篇 下一篇

猜你喜欢

热点阅读