美文网首页
圣杯布局和双飞翼布局

圣杯布局和双飞翼布局

作者: 肉肉肉肉_包 | 来源:发表于2019-09-25 18:11 被阅读0次

    圣杯布局

    <div class="container">
        <div class="center">我是中间</div> 
        <div class="left">我是左边</div>
        <div class="right">我是右边</div>      
    </div>
    
    .container{
          padding: 0 200px 0 200px;
          height: 100px;
          background: #cfd;
        }
        .center{
          float: left;
          width: 100%;
          background: pink;
        }
        .left{
          float: left;
          width: 200px;
          background: yellow;
        }
        .right{
          float: left;
          width: 200px;
          background: #eee;
        }
    
    image.png

    得到的结果是这样的,相当于把整个屏幕分成了三个部分,三个div都浮动,这个时候由于center部分独占一行,所以左右两个div被挤到下面。

    由于浮动元素上边缘会去紧贴当前盒子的上边缘或者是之前浮动元素的下边缘,左浮动框的左边缘会去贴包含框的左边缘,或者他之前的左浮动框的右边缘。如果当前行剩余的空间容不下一个浮动框,他就会换行。

    .left{
          float: left;
          width: 200px;
          background: yellow;
          margin-left: -100%;
        }
    
    image.png

    这是因为margin设置百分比是相对于父级元素,这个时候就相当于container的宽度,那么就左移container的宽度,这个时候就移动到中间元素的左边。

    .left{
          float: left;
          width: 200px;
          background: yellow;
          margin-left: -100%;
          position: relative;
          right: 200px;
        }
    
    image.png

    这个时候左边元素就移动到左边
    使用相对定位是因为设置绝对定位会使得float失效
    1.当position为absolute/fixed时,元素已脱离文档流,再对元素应用float失效(即不起作用)。
    2.当position为static/relative时,元素依旧处于普通流中,再对元素应用float起作用。
    同理设置右边元素

    .right{
          float: left;
          width: 200px;
          background: #eee;
          /*margin-right: -100%;*/
          margin-right: -200px;
          /*margin-left: -100%;
          position: relative;
          left: 100%;*/
        }
    
    image.png
    注意:必须设置中间元素的宽度为100%,因为此时中间元素也为浮动元素,由于浮动具有包裹性,在不显式设置宽度的情况下会自动“收缩”到内容的尺寸大小,无法实现自适应。

    双飞翼布局

    <style>
    .container{
          width: 100%;
          float: left;
        }
        .center{
          padding: 0 200px 0 200px;
          height: 100px;
          width: 100%;
          background: #cfd;
        }
        .left{
          float: left;
          width: 200px;
          background: pink;
          height: 100px;
          margin-left: -100%;
        }
        .right{
          float: left;
          width: 200px;
          background: #eee;
          height: 100px;
          margin-left: -200px;
        }
    </style>
    <div class="container">
        <div class="center">我是中间</div> 
    </div>
    <div class="left">我是左边</div>
    <div class="right">我是右边</div>
    

    相关文章

      网友评论

          本文标题:圣杯布局和双飞翼布局

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