美文网首页Web前端之路CSS让前端飞
圣杯布局、双飞翼布局,你懂了吗?

圣杯布局、双飞翼布局,你懂了吗?

作者: 白日做梦的咸鱼 | 来源:发表于2019-12-08 23:32 被阅读0次

    圣杯布局和双飞翼布局

    在如今的网页中我们经常可以看到左、中、右三列,其中左右两列宽度固定,中间宽度自适应的布局方式,如下图。圣杯布局和双飞翼布局就是这种三列布局的两种实现方式。


    1575789288547.png

    圣杯布局和双飞翼布局的实现都利用了以下两个技术:

    1、float:浮动,利用浮动可以使元素脱离文档流,从而让块级元素在同一行排列。

    2、负margin:在left 和 top方向上的负margin值可以将元素自身向相应方向位移。

    圣杯布局

    html

    <header>
            <h1 style="text-align: center;">这是一个三列布局</h1>
        </header>
        <main>
            <div class="center"><p>center</p></div>
            <div class="left"><p>这里是左边部分</p></div>
            <div class="right"><p>这里是右边部分</p></div>
        </main>
        <footer>
            <footer style="text-align: center;"><h2>footer</h2></footer>
        </footer>
    

    css

    main{
            padding: 0 300px;
        }
        main::after{
            content: "";
            display: block;
            clear: both;
        }
        main div{
            float: left;
        }
        .center{
            width: 100%;
            background-color: blue;
        }
        .left{
            width: 300px;
            background-color: red;
            margin-left: -100%;
            position: relative;
            left: -300px;
        }
        .right{
            width: 300px;
            background-color: yellow;
            margin-left: -300px;
            position: relative;
            left: 300px;
        }
    

    源码

    双飞翼布局

    html

    <header>
      <h1 style="text-align: center;">这是一个三列布局</h1>
    </header>
    <main>
      <div class="center">
        <div class="center-content">
           <p>center</p>
        </div>
      </div>
      <div class="left">
        <p>这里是左边部分</p>
      </div>
      <div class="right">
        <p>这里是右边部分</p>
      </div>
    </main>
    <footer>
      <footer style="text-align: center;">
        <h2>footer</h2>
      </footer>
    </footer>
    

    css

    main::after {
      content: "";
      display: block;
      clear: both;
    }
    main > div {
      float: left;
    }
    .center {
      width: 100%;
    }
    .center-content{
      margin: 0 300px;
      background-color: blue;
      overflow:auto;
    }
    .left {
      width: 300px;
      background-color: red;
      margin-left: -100%;
    }
    .right {
      width: 300px;
      background-color: yellow;
      margin-left: -300px;
    }
    

    源码

    区别

    不仔细看,会感觉这两个布局不是一样的吗?没有发现差异的话不妨先仔细看一下上面的代码并思考一下差异。

    其实他们的区别在于,使center部分的内容不被left和right部分给遮挡的处理方式。
    1、圣杯布局是在父容器main上加在左右padding(左右部分的宽度 px),再利用定位调整left 和 right的位置。

    2、双飞翼布局是通过在center部分种添加一个center子块(center-content)让它的左右margin 等于左右部分的宽度。

    ps:圣杯布局在center的宽度小于left right部分的宽度时,布局会乱。

    最后

    在flex和grid 布局出现的今天实现类似的三列布局已经非常简单,但是如果考虑到兼容性问题的话,基于浮动的这两种布局方式还是需要了解的。最后谢谢各位小伙伴阅读文章,如有错误还望指出。

    相关文章

      网友评论

        本文标题:圣杯布局、双飞翼布局,你懂了吗?

        本文链接:https://www.haomeiwen.com/subject/fymvgctx.html