5 種常用佈局的 flex 實現

meikidd發表於2017-11-29

Sticky Footer

經典的上-中-下佈局。

當頁面內容高度小於可視區域高度時,footer 吸附在底部;當頁面內容高度大於可視區域高度時,footer 被撐開排在 content 下方

demo link

demo 1 - Sticky Footer
demo 1 - Sticky Footer

<body>
  <header>HEADER</header>
  <article>CONTENT</article>
  <footer>FOOTER</footer>
</body>複製程式碼
body {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}
article {
  flex: auto;
}複製程式碼

Fixed-Width Sidebar

在上-中-下佈局的基礎上,加了左側定寬 sidebar。

demo link

demo 2 - Fixed-Width Sidebar
demo 2 - Fixed-Width Sidebar

<body>
  <header>HEADER</header>
  <div class="content">
    <aside>ASIDE</aside>
    <article>CONTENT</article>
  </div>
  <footer>FOOTER</footer>
</body>複製程式碼
body {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}
.content {
  flex: auto;
  display: flex;
}
.content article {
  flex: auto;
}複製程式碼

Sidebar

左邊是定寬 sidebar,右邊是上-中-下佈局。

demo link

demo 3
demo 3

<body>
  <aside>ASIDE</aside>
  <div class="content">
    <header>HEADER</header>
    <article>CONTENT</article>
    <footer>FOOTER</footer>
  </div>
</body>複製程式碼
body {
  min-height: 100vh;
  display: flex;
}
aside {
  flex: none;
}
.content {
  flex: auto;
  display: flex;
  flex-direction: column;
}
.content article {
  flex: auto;
}複製程式碼

Sticky Header

還是上-中-下佈局,區別是 header 固定在頂部,不會隨著頁面滾動。

demo link

demo 4 - Sticky Header
demo 4 - Sticky Header

<body>
  <header>HEADER</header>
  <article>CONTENT</article>
  <footer>FOOTER</footer>
</body>複製程式碼
body {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  padding-top: 60px;
}
header {
  height: 60px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  padding: 0;
}
article {
  flex: auto;
  height: 1000px;
}複製程式碼

Sticky Sidebar

左側 sidebar 固定在左側且與視窗同高,當內容超出視窗高度時,在 sidebar 內部出現滾動條。左右兩側滾動條互相獨立。

demo link

demo 5 - Sticky Sidebar
demo 5 - Sticky Sidebar

<body>
  <aside>
    ASIDE
    <p>item</p>
    <p>item</p>
    <!-- many items -->
    <p>item</p>
  </aside>
  <div class="content">
    <header>HEADER</header>
    <article>CONTENT</article>
    <footer>FOOTER</footer>
  </div>
</body>複製程式碼
body {
  height: 100vh;
  display: flex;
}
aside {
  flex: none;
  width: 200px;
  overflow-y: auto;
  display: block;
}
.content {
  flex: auto;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}
.content article {
  flex: auto;
}複製程式碼

相關文章