在flexbox中切换从竖屏到横屏布局

5
我想用flexbox实现下面的布局:Layout,如图所示,左侧为竖屏视图,右侧为横屏视图。
前提是我希望尽可能地保持html的简短(如果可能的话)。
有没有一种使用flex的方法来实现呢?
在竖屏视图中,一切都很正常,因为只有一列。
现在我被卡在了横屏方向上。
导航应该在屏幕的右侧,其他内容应该在左侧。

header, footer, main, nav {
  margin: 5px;
  padding: 5px;
  border-radius: 5px;
  min-height: 120px;
  border: 1px solid #eebb55;
  background: #ffeebb;
}
section {
  display: flex;
  flex-direction: column;
}
@media only screen and (orientation: landscape) {
  /* no clue */
}
<section>
  <header>header</header>
  <main>content</main>
  <nav>navigation</nav>
  <footer>footer</footer>
</section>

非常感谢您的时间!

好的,你的解决方案对于这个问题很有效。但是我现在需要为两侧分别设置滚动条,我认为使用html语法不可能实现这一点。我必须操作DOM。将导航栏移出并将部分和导航高度设置为100vh,并将溢出设置为滚动。Flex和Grid不适合我的问题。我有点失望。但是非常感谢@Michael_B ;) - ruslansteiger
2个回答

10

为了使用 flexbox 布局,容器必须有固定的高度。否则,flex 项目不知道在何处换行,导航元素也不会移到右侧列中。

在这种情况下,布局似乎覆盖了视口,所以您应该可以直接使用 height: 100vhorder 属性。无需更改 HTML。

section {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

header, footer, main, nav {
  flex: 1;
  margin: 5px;
  padding: 5px;
  border-radius: 5px;
  border: 1px solid #eebb55;
  background: #ffeebb;
}

@media only screen and (orientation: landscape) {
  section {
    flex-wrap: wrap;
  }
  nav {
    flex-basis: 100%;
    order: 1
  }
}

body { margin: 0; }
<section>
  <header>header</header>
  <main>content</main>
  <nav>navigation</nav>
  <footer>footer</footer>
</section>

jsfiddle演示

其他选项请参见:在网格中使一个div跨越两行


3
如果你无法为 section 设定固定高度,可以通过将 navigaton 设置为绝对定位的方式进行操作。

header, footer, main, nav {
  margin: 5px;
  padding: 5px;
  border-radius: 5px;
  min-height: 120px;
  border: 1px solid #eebb55;
  background: #ffeebb;
}
section {
  display: flex;
  flex-direction: column;
}
@media only screen and (orientation: landscape) {
  section {
    position: relative;
  }
  header, footer, main {
    width: calc(60% - 10px);         /*  10px is for the margin  */
    box-sizing: border-box;
  }
  nav {
    position: absolute;
    top: 0;
    min-height: calc(100% - 10px);   /*  10px is for the margin  */
    right: 0;
    width: calc(40% - 10px);         /*  10px is for the margin  */
    box-sizing: border-box;
  }
}
<section>
  <header>header</header>
  <main>content</main>
  <nav>navigation</nav>
  <footer>footer</footer>
</section>


是的,谢谢,这个也可以。但现在我想让两边都有单独的滚动条。我认为这是不可能的,除非进行DOM操作。:( 我很失望。但还是感谢您的时间 @LGSon - ruslansteiger
1
@SuddenlyRust 当然可以有单独的滚动条。是内容和导航都应该滚动吗? - Asons
页头 + 主体 + 页脚应该有一个滚动条(位于屏幕左侧),而导航则位于屏幕右侧。 - ruslansteiger
1
@SuddenlyRust 在这里回答了你的问题:https://dev59.com/jFcP5IYBdhLWcg3ww8qS - Asons

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接