使用 flex 实现几种常用布局(一)

大家好,我是雷布斯。

网页布局是前端面试中很常见的面试方向,传统的布局方案是基于 display + position + float属性,实现一些特殊的布局都会比较麻烦。

W3C 在 2009 年就提出了 Flex 布局,可以简便、完整、响应式地实现各种页面布局,也成为了目前主流的布局方案。

想必大家都已经很了解 Flex 的基本使用方法,今天给大家介绍几种常用的布局实现。

Sticky Footer

首先来看看经典的上-中-下布局。

布局特点:

  • 当页面内容高度小于可视区域高度时,footer 吸附在底部;
  • 当页面内容高度大于可视区域高度时,footer 被撑开排在 content 下方

大家有实现思路吗?

其实使用 flex 实现很简单,咱们也不卖关子,直接贴出代码:

<body>
  <header>HEADER</header>
  <article>CONTENT</article>
  <footer>FOOTER</footer>
</body>
body {
  min-height100vh;
  display: flex;
  flex-direction: column;
}
article {
  flex: auto;
}

是不是很简单?

flex: auto;flex:1 1 auto; 的简写,有剩余空间就放大,空间不够就缩小。

那么它和 flex: 1; 有什么区别呢,大家可以思考下。

Fixed-Width Sidebar

上-中-下布局的基础上,加上左侧定宽 sidebar。

我们依旧可以使用 flex: auto实现。

<body>
  <header>HEADER</header>
  <div class="content">
    <aside>ASIDE</aside>
    <article>CONTENT</article>
  </div>
  <footer>FOOTER</footer>
</body>
body {
  min-height100vh;
  display: flex;
  flex-direction: column;
}
.content {
  flex: auto;
  display: flex;
}
.content aside {
  width100px;
}
.content article {
  flex: auto;
}

Sidebar

左边是定宽 sidebar,右边是上-中-下布局。

<body>
  <aside>ASIDE</aside>
  <div class="content">
    <header>HEADER</header>
    <article>CONTENT</article>
    <footer>FOOTER</footer>
  </div>
</body>
body {
  min-height100vh;
  display: flex;
}
aside {
  flex: none;
}
.content {
  flex: auto;
  display: flex;
  flex-direction: column;
}
.content article {
  flex: auto;
}

Sticky Header

还是 上-中-下 布局,区别是 header 固定在顶部,不会随着页面滚动。

<body>
  <header>HEADER</header>
  <article>CONTENT</article>
  <footer>FOOTER</footer>
</body>
body {
  min-height100vh;
  display: flex;
  flex-direction: column;
  padding-top60px;
}
header {
  height60px;
  position: fixed;
  top0;
  left0;
  right0;
  padding0;
}
article {
  flex: auto;
  height1000px;
}

大家可能还会想到使用 sticky 替换 fixed

Sticky Sidebar

布局要点:

  • 左侧 sidebar 固定在左侧且与视窗同高
  • 当内容超出视窗高度时,在 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 {
  height100vh;
  display: flex;
}
aside {
  flex: none;
  width200px;
  overflow-y: auto;
  display: block;
}
.content {
  flex: auto;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}
.content article {
  flex: auto;
}

最后

篇幅限制,我们的第一篇先介绍到这儿。我们将在下一篇介绍其他的一些布局实现方式,比如如何单独适配最后一行的排列实现色子5的布局实现色子3的布局等布局。

还没有使用过我们刷题网站(https://fe.ecool.fun/)或者刷题小程序的同学,如果近期准备或者正在找工作,千万不要错过,我们的题库主打无广告和更新快哦~。

老规矩,也给我们团队的辅导服务打个广告。