在较小的屏幕上交换 <nav> 和 <section> 的位置

Swap position of <nav> and <section> on smaller screens

我的页面中有这样的内容:

<header>
    <nav>
        a menu...
    </nav>
</header>
<section>
    some block...
</section>
<section>
    <article>
        article content...
    </article>
    rest of the page...
</section>

这是一个标准的网页布局结构:菜单在顶部,然后是主要主题部分(第一个 <section>),然后是页面的其余部分(第二个 <section>)。在桌面上看没问题。

问题:可以在移动设备上用第一个 section 块替换 CSS navigation 块,这样主要主题就会在主菜单上方?

您可以使用 @media 隐藏 nav。尝试放大此 fiddle

@media screen and (max-width: 600px) {
    nav {
        display:none;
    }
}
<header>
    <nav>a menu...</nav>
</header>
<section>some block...</section>
<section>
    <article>article content...</article>rest of the page...</section>

Ypu 可以使用 (i) CSS 媒体查询 (ii) CSS flexbox (iii) order 属性 在不改变 HTML 的情况下交换元素的顺序:

/*
 * change order of header and sections on smaller screens using CSS flex
 * use the stack snippet Full page button to view the "desktop" version
 */
@media only screen and (max-width: 700px) {
  #wrapper {
    display: flex;
    flex-direction: column;
  }
  section:nth-of-type(1) {
    order: 1;
  }
  header {
    order: 2;
  }
  section:nth-of-type(2) {
    order: 3;
  }
}
<div id="wrapper">
  <header>
    <nav>Navbar</nav>
  </header>
  <section>Section 1</section>
  <section>Section 2</section>
</div>