【问题标题】:Sidebar with two flexbox navs top and bottom带有顶部和底部两个 flexbox 导航的侧边栏
【发布时间】:2018-10-28 20:02:32
【问题描述】:

我正在尝试使用 flexbox 对齐侧边栏中的两个导航(视口高度为 100%)。

  • 红色框应放在其侧边栏父级的顶部
  • 底部的蓝色框。

如果红色导航变大并且两者之间的空间很小,侧边栏应该可以在 y 轴上滚动。我尝试过为两者设置顶部和底部边距,但没有运气。有人可以帮帮我吗?

谢谢!

html, body {
  margin: 0;
}

* {
  box-sizing: border-box;
}

.sidebar {
  height: 100vh;
  width: 300px;
  background: #ccc;
  padding: 10px;
  overflow-y: scroll;
}

.sidebar__top {
  background: red;
  height: 200px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.sidebar__bottom {
  background: blue;
  height: 100px;
  margin-top: auto;
}
<aside class="sidebar">
  <nav class="sidebar__top"></nav>
  <nav class="sidebar__bottom"></nav>
</aside>

这是我的小提琴:http://jsfiddle.net/1dw7h2sp/1/

【问题讨论】:

  • 所以你也想让红框填满剩余的空间,或者如果有一些灰色的间隙也可以?
  • 嗨 lumio,如果红色填补空白也没关系 ;)
  • 即使没有,删除 flex-grow 也可以解决问题(如我的回答中所述):)
  • 非常感谢!

标签: css flexbox


【解决方案1】:

可能还有其他方法可以做到这一点。简而言之,我做了以下事情:

  1. 用能够扩大大小的父元素包裹元素 (.sidebar__wrapper)
  2. 设置 min-height 而不是 height 以便它可以增长
  3. 如果您希望元素填充剩余空间,请使用 flex-grow

html, body {
  margin: 0;
}

* {
  box-sizing: border-box;
}

.sidebar {
  height: 100vh;
  width: 300px;
  background: #ccc;
  overflow-y: scroll;
  
  margin: 0;
  padding: 0;
}

/* set up a wrapper that can grow in size */
.sidebar__wrapper {
  height: auto;
  min-height: 100vh;
  width: 100%;
  background: #808080;
  
  padding: 10px;
  margin: 0;
  
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.sidebar__top {
  background: red;
  min-height: 200px;
  margin-bottom: 10px;
  
  /* this fills up the remaining space */
  flex-grow: 1;
}

.sidebar__bottom {
  background: blue;
  min-height: 100px;
}
<aside class="sidebar">
  <div class="sidebar__wrapper">
    <nav class="sidebar__top" contenteditable="true">
      <p>test</p>
    </nav>
    <nav class="sidebar__bottom"></nav>
  </div>
</aside>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-17
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 2020-01-29
    • 1970-01-01
    • 2019-02-28
    • 2019-11-03
    相关资源
    最近更新 更多