如何在flex布局中使用固定位置?

新手上路,请多包涵

我有一个包含两列的 flexbox 布局。

左栏是固定的,而右栏是可滚动的。

你怎么能那样做?

看看下面的代码:

 #parent {
  display: flex;
}
#left {
  flex-grow: 1;
}
#left div {
  position: fixed;
  background: blue;
  top: 0;
  left: 0;
  height: 100vh;
}
#right {
  flex-grow: 5;
  background: red;
  height: 300vh;
}
 <div id="parent">
  <div class="child" id ="left">
    <div>
      ABC
    </div>
  </div>
  <div class="child" id ="right">
  DEF
  </div>
</div>

小提琴

原文由 heroxav 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 808
2 个回答

如果我了解您的要求,您希望右侧滚动并固定左侧。这可以在不使用固定位置的情况下完成。

我个人也建议不要使用固定位置,除非它是绝对必要的,因为它可能在移动设备上有一些不需要的行为,并且你有点失去非定位解决方案的好处,比如 flexbox 提供。

 html, body {
  margin: 0;
}
#parent {
  display: flex;
  height: 100vh;
}
#left {
  flex-grow: 1;
  background: blue;
}
#right {
  flex-grow: 5;
  background: red;
  overflow: auto;
}
#right div {
  height: 300vh;
}
 <div id="parent">
  <div class="child" id ="left">
      ABC
  </div>
  <div class="child" id ="right">
    <div>
      DEF
    </div>
  </div>
</div>

原文由 Asons 发布,翻译遵循 CC BY-SA 3.0 许可协议

干得好

 #parent {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  display: flex;
  align-items: stretch;
}
#left {
  flex-grow: 1;
  background: lightgray;
}
#right {
  flex-grow: 5;
  background: red;
  overflow-y: auto;
}
.scroll {
  height: 300vw;
}
 <div id="parent">
  <div class="child" id="left">
    <div>
      ABC
    </div>
  </div>
  <div class="child" id="right">
    <div class="scroll">
      DEF
    </div>
  </div>
</div>

原文由 Rudi Urbanek 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏