聖盃佈局經常使用兩種方法

聖盃佈局經常使用兩種方法

首先搭建起始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

總結:兩種方法相比,顯然,第二種方法更簡單好用,第一種方法雖然爲經典方法,但相比於第二種較爲複雜,因此,經典的不必定是最好的,我的強烈建議用第二種。
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息