【问题标题】:Responsive flexbox layout: reordering elements响应式 flexbox 布局:重新排序元素
【发布时间】:2018-11-02 04:51:47
【问题描述】:

我正在尝试实现如图所示的响应式布局,左侧是移动设备,右侧是桌面。如果我可以为包装器设置一个固定的高度,那么使用 flexbox 会相对容易,但是因为内容是动态的,所以这是不可能的。

另一种解决方案是在元素 C 上使用绝对位置,但这似乎很 hacky,我希望找到一个更优雅的解决方案。

这是代码的框架:

.wrapper {
    display: flex;
    flex-direction: column;
  }

@media(min-width: 800px) {
  .wrapper {
    flex-direction: row;
    flex-wrap: wrap;
  }
}

.section {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 36px;
}

.section-a {
  background: green;
  height: 200px;
}

@media(min-width: 800px) {
  .section-a {
    flex-basis: 33%;
  }
}

.section-b {
  background: yellow;
  height: 400px;
}

@media(min-width: 800px) {
  .section-b {
    flex-basis: 66%;
  }
}

.section-c {
  background: blue;
  height: 200px;
}

@media(min-width: 800px) {
  .section-c {
    flex-basis: 33%;
  }
}
<div class="wrapper">
  <div class="section section-a">A</div>
  <div class="section section-b">B</div>
  <div class="section section-c">C</div>
</div>

感谢您的帮助!

【问题讨论】:

  • 我将为此使用 CSS-Grid...我确信这已经被覆盖过...我会看看我是否能找到一个重复的。
  • @syberen 检查我的更新答案
  • 我认为 flex 使用你的布局是不可能的,而不会给包装器添加某种高度限制,但也许这会给你一些想法:stackoverflow.com/questions/19574851/…
  • 即使内容是动态的,是什么阻止您使用overflow-y: auto 或仅使用overflow: auto?我个人还是会选择 Flexbox。
  • 有趣的想法,没有考虑到。我明天试试看。

标签: css flexbox


【解决方案1】:

您可以使用grid 实现此目的。我已经简化了你的代码并删除了不需要的css

.wrapper {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: [row1-start] auto [row2-start] auto [row2-end];
}

.section {
  padding: 20px;
  display: flex;
  align-items: center;
}
.section-a {
  height: 50px;
  background-color: green;
}  
.section-b {
  grid-row: row1-start / row2-end;
  grid-column: 2/-1;
  background-color: yellow;
}
.section-c {
  background-color: blue;
  height: 180px;
}
<div class="wrapper">
  <div class="section section-a">A</div>
  <div class="section section-b">B</div>
  <div class="section section-c">C</div>
</div>

工作小提琴here

【讨论】:

  • 谢谢,我会研究一下这个方法。由于浏览器的支持,到目前为止我一直担心使用 CSS 网格。
  • @syberen 如果这解决了您的问题,请将此答案标记为“已接受”。这将激励我们为社区做出更多贡献。
【解决方案2】:

编辑:这是一种尝试,因为我误解了 OP 的问题。我的答案是给定的.wrapperheight

使用具有以下属性的 flex 的解决方案:

此代码适用于您的桌面布局:

.wrapper {
    width: 100%;
    height: 100vh;
    display: flex;
    flex-flow: column wrap;
}

.section {
    width: 50%;
    border: 1px solid black;
    box-sizing: border-box;
}

.section-a {
    height: 25vh; // for example
}

.section-b {
    order: 3;
    flex-basis: 100%;
}

.section-c {
    flex-grow: 1;
}
<div class="wrapper">
    <div class="section section-a">A</div>
    <div class="section section-b">B</div>
    <div class="section section-c">C</div>
</div>

【讨论】:

  • OP 想要一个基于 a 和 c 的动态高度 - 这固定为 100vh。 来自问题: 如果我可以为包装器设置一个固定高度,那么使用 flexbox 会相对容易,但是因为内容是动态的,所以这是不可能的。
  • 感谢您抽出宝贵时间!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-12
  • 1970-01-01
  • 1970-01-01
  • 2020-05-16
  • 2018-03-19
  • 2015-09-27
  • 2020-04-12
相关资源
最近更新 更多