经典的三栏布局:圣杯布局,双飞翼布局,flex布局

需求:
两边栏固定宽度,中间宽度自适应,一般左边栏为导航,右边栏为广告,中间栏为主要内容的展示,div块上中间栏放在第一位,重要的东西放在文档流前面可以优先渲染。

圣杯布局和双飞翼布局的共同特点都是利用float+margin的负值来实现并列的结构。首先中间栏width 100%后,左右栏被挤在第二行,左栏margin-left设置为-100%后(实际即为中间栏的宽度),这样左栏就跟中间栏并列,且左栏和中间栏的左边缘对其,同理右栏margin-left(因为float是向左的)设置为右栏自己宽度的负值,这样就升上去,且右边缘和中间栏的右边栏重合。

现在的问题就是左右栏占用了main的空间。圣杯布局和双飞翼的布局的处理差异也就在这里:

1.圣杯布局

圣杯布局的处理方式为父容器container设置padding-left和padding-right为左右栏的宽度,此时左右栏会表现往里面缩一些,因为padding只是调节内部元素的位置并不会显示width的content(盒子模型),对外部元素没影响。此时就需要用相对定位调节左右栏left和right为父容器pading左右值的负值,这样就移开了左右栏对中间栏的占据,且中间栏的内容全部显示在width的content中。

代码:

<!-- 圣杯布局 -->
<!DOCTYPE html>
<html>

<head>
  <style>
    .left {
      background: #E79F6D;
      width: 150px;
      float: left;
    }

    .main {
      background: #D6D6D6;
      width: 100%;
      float: left;
    }

    .right {
      background: #77BBDD;
      width: 190px;
      float: left;
    }
    .left {
      margin-left: -100%;
    }
    .right{
      margin-left:-190px;
    }
    /* 设置padding后,margin是不占用其他元素的padding的,padding只是用来调节内部元素与本身的距离,margin调节才是本身与周围之间的距离 */
    .con {
      padding-left: 150px;
      padding-right: 190px;
    }
    .left {
      position: relative;
      left: -150px;
    }
    .right {
      position: relative;
      right: -190px;
    }
  </style>
</head>

<body>
  <div class="con">
    <div class="main">Main</div>
    <div class="left">Left</div>
    <div class="right">Right</div>
  </div>
</body>

</html>

2. 双飞翼布局

双飞翼并列的方式与圣杯布局相同,但是摈弃了相对定位的方式。而是给中间栏加了一个父容器,父容器设置float,子容器设置margin-left和margin-right抵消左右栏布局的宽度,避免content显示部分被左右栏覆盖到自己宽度。(注意不是float左右因为margin移动了,而是是中间栏的content的内容width一部分宽度分给了margin,自己缩小了,float是脱离的文档流的,无视block,但是受影响到文字,参考文字环绕)。

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        .main-wrapper {
            float: left;
            width: 100%;
        }
        .main {
            height: 300px;
            /* 多10px间距 */
            margin-left: 210px;
            margin-right: 190px;
            background-color: rgba(255, 0, 0, .5);
        }
        .sub {
            float: left;
            width: 200px;
            height: 300px;
            margin-left: -100%;
            background-color: rgba(0, 255, 0, .5);
        }
        .extra {
            float: left;
            width: 180px;
            height: 300px;
            margin-left: -180px;
            background-color: rgba(0, 0, 255, .5);
        }
    </style>
</head>
<body>
    <div class="main-wrapper">
        <div class="main"></div>
    </div>
    <div class="sub"></div>
    <div class="extra"></div>

</body>
</html>

先进而简单的flex布局

待续。。。。

猜你喜欢

转载自www.cnblogs.com/zhangmingzhao/p/9332174.html