首页 > 解决方案 > 在不同的分辨率下改变 flexbox-direction

问题描述

为什么在低于 800px 的分辨率下,flex-direction 没有改变?这些项目仍然在一行上。如果我想更改不同分辨率的顺序,也会发生同样的事情。

这是HTML和CSS:

body {
  font-weight: bold;
  text-align: center;
  font-size: 16px;
  box-sizing: border-box;
}

main {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

article,
.aside {
  border: 1px solid black;
}

article {
  width: 50%;
}

.aside {
  width: 24%;
}

@media screen and (max-width: 800px) {
  main {
    flex-direction: column;
  }
  main>* {
    width: 100%;
  }
}
<body>
  <main>
    <article class="main-article">
      <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. </p>
    </article>
    <aside class="aside aside-1">Aside 1</aside>
    <aside class="aside aside-2">Aside 2</aside>
  </main>
</body>

标签: htmlcssflexboxmedia-queries

解决方案


flex 方向实际上正在正确更改,问题是您.aside在媒体查询之外和媒体查询内部都有类,您正在使用*for 通配符。类将始终优先于通配符。.aside因此,即使在小于 800 像素的情况下,您实际上也将项目制作为24%。

body {
  font-weight: bold;
  text-align: center;
  font-size: 16px;
  box-sizing: border-box;
}

main {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

article,
.aside {
  border: 1px solid black;
}

article {
  width: 50%;
}

.aside {
  width: 24%;
}

@media screen and (max-width: 800px) {
  main {
    flex-direction: column;
  }
  main > *,
  main > .aside {
    width: 100%;
    border-color: yellow;
  }
}
<body>
  <main>
    <article class="main-article">
      <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. </p>
    </article>
    <aside class="aside aside-1">Aside 1</aside>
    <aside class="aside aside-2">Aside 2</aside>
  </main>
</body>

如您所见,侧面现在是全宽的,并且在列方向上。


推荐阅读