在flexbox中从纵向切换到横向布局

时间:2017-05-15 21:19:13

标签: html css css3 flexbox

我想通过flexbox跟踪Layout

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>

非常感谢你的时间!

2 个答案:

答案 0 :(得分:6)

要使此布局与flexbox一起使用,容器上必须有固定的高度。否则,flex项目不知道换行的位置,nav元素也不会移到右列。

在这种情况下,布局似乎覆盖视口,因此您应该全部设置。

只需使用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>

https://jsfiddle.net/aysogmqh/1/

答案 1 :(得分:2)

如果您无法在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>

相关问题