圣杯布局经常使用两种方法

圣杯布局经常使用两种方法

首先搭建起始HTML结构及设置基本css样式

<body>
  <div class="header">header</div>
  <div class="main">
      <div class="content">content</div>
      <div class="left">left</div>
      <div class="right">right</div>
  </div>
  <div class="footer">footer</div>
</body>
<style>
      * {
          margin: 0;
          padding: 0;
      }
      .header,.footer {
          height: 100px;
          background: #000;
          color:seashell;
      }
      .main {
          height: 400px;
          background: #ccc;
      }
      .content {
          height: 400px;
          background: #f90;
      }
      .left {
          width: 300px;
          height: 400px;
          background: purple;
      }
      .right {
          width: 300px;
          height: 400px;
          background: seagreen;
      }
  </style>
要实现的效果图以下:

a1YjSS.png

1.经典方法 (浮动)

<style>
      * {
          margin: 0;
          padding: 0;
      }
      .header,.footer {
          height: 100px;
          background: #000;
          color:seashell;
      }
      .main {
          height: 400px;
          background: #ccc;
      }
      .content {
          height: 400px;
          background: #f90;
          float: left;
          width: 100%;
      }
      .left {
          width: 300px;
          height: 400px;
          background: purple;
          float: left;
          margin-left: -100%;
      }
      .right {
          width: 300px;
          height: 400px;
          background: seagreen;
          float: left;
          margin-left: -300px;
      }
  </style>

这个方法中首先在main这个父盒子中不按常规的思惟,将content放在最上面(常规思惟应该是left在最上面),这也是这个方法的妙处之一。首先main里面的三个盒子都设置为左浮动,而后设置content的width为100%,最后用margin-left将left和right两个盒子分列content左右,也就实现了圣杯布局。css

2.flex布局

<style>
      * {
          margin: 0;
          padding: 0;
      }
      .header,.footer {
          height: 100px;
          background: #000;
          color:seashell;
      }
      .main {
          height: 400px;
          background: #ccc;
          display: flex;
      }
      .content {
          height: 400px;
          background: #f90;
          flex: auto;
      }
      .left {
          width: 300px;
          height: 400px;
          background: purple;
          flex: none;
      }
      .right {
          width: 300px;
          height: 400px;
          background: seagreen;
          flex: none;
      }
  </style>

相比于第一种方法,用flex符合属性来作就轻松不少,就加了四行代码,main变为伸缩盒子,content,left,right依次设为flex:auto; flex:none; flex:none;shell

说明:flex 是复合属性,是 flex-grow , flex-shrinkflex-basis 的简写,默认值为 0 1 auto布局

  • 若是缩写为 flex: 1 , 则其计算值为 1 1 0%flex

  • 若是缩写 flex: auto , 则其计算值为 1 1 autospa

  • 若是flex: none , 则其计算值为0 0 autocode

总结:两种方法相比,显然,第二种方法更简单好用,第一种方法虽然为经典方法,但相比于第二种较为复杂,因此,经典的不必定是最好的,我的强烈建议用第二种。
相关文章
相关标签/搜索
本站公众号
   欢迎关注本站公众号,获取更多信息