CSS Grid达到特定大小时会自动换行

Mur*_*man 5 html css css3 flexbox css-grid

所以我正在创建一个布局

<div id="structure-content">
<main>content goes here</main>
<aside>aside content</aside>
</div>
Run Code Online (Sandbox Code Playgroud)

I want the aside to be a quarter of the width and to automatically wrap to below the main once it hits a certain size and the main to take the full width. I know I can do this with media queries but people are saying that it can be done with grid and no media queries. I have been experimenting and researching for hours and cannot work it out. Any ideas? If it cannot be done then that is fine and I can try it with flexbox or media queries.

Props in advance.

Sar*_*ana 5

div达到特定大小的以下代码将自动下降。如果要降低div的特定大小,我们仅需使用媒体查询。

#structure-content {
    margin-bottom: 1em;
    background: #fff;
    color: #fff;
    padding: 1.5em 1em;
    display: flex;
    flex-wrap: wrap;
    flex-direction: row;
}

main {
    background: green;
}

aside {
    background: blue;
}

main,
aside {
    flex: 1 0 15em;
    margin-left: 0.5em;
    margin-right: 0.5em;
}
Run Code Online (Sandbox Code Playgroud)
<div id="structure-content">
    <main>content goes here</main>
    <aside>aside content</aside>
</div>
Run Code Online (Sandbox Code Playgroud)


kuk*_*kuz 4

使用 CSS 网格,您可以使用mainaside来获取可用宽度的一半,并在任一网格项达到最小宽度时自动换行- 请参阅下面的演示:grid-template-columns: repeat(auto-fit, minmax(300px, 1fr))

body {
  margin: 0;
}
#structure-content {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
}
main {
  background: aliceblue;
}
aside {
  background: cadetblue;
}
Run Code Online (Sandbox Code Playgroud)
<div id="structure-content">
  <main>content goes here</main>
  <aside>aside content</aside>
</div>
Run Code Online (Sandbox Code Playgroud)


解决方案

有了 CSS Grid,我想说你可以使用媒体查询。无论如何,Flexbox在这里会很好用:

  • 使用包装弹性盒
  • min-width为每个aside和保留一个,main并添加flex: 1以将其弯曲到剩余空间(如果可用) - 请参阅下面的演示:

body {
  margin: 0;
}
#structure-content {
  display: flex;
  flex-wrap: wrap; /* a wrapping flexbox */
}
main {
  background: aliceblue;
  min-width: 75vw; /* forces aside to take one-fourth space */
  flex: 1;
}
aside {
  background: cadetblue;
  min-width: 250px; /* minimum width of aside */
  flex: 1;
}
Run Code Online (Sandbox Code Playgroud)
<div id="structure-content">
  <main>content goes here</main>
  <aside>aside content</aside>
</div>
Run Code Online (Sandbox Code Playgroud)