【问题标题】:CSS Grid auto-wrap aside when it gets to a certain size当 CSS Grid 达到一定大小时,它会自动换行
【发布时间】:2019-08-08 12:41:24
【问题描述】:

所以我正在创建一个布局,我有一个

<div id="structure-content">
<main>content goes here</main>
<aside>aside content</aside>
</div>

我希望侧面是宽度的四分之一,并在达到一定尺寸后自动包裹到主体下方,而主体占据整个宽度。我知道我可以用媒体查询来做到这一点,但人们说它可以用网格来完成,没有媒体查询。我已经试验和研究了几个小时,但无法解决。有任何想法吗?如果无法完成,那很好,我可以尝试使用 flexbox 或媒体查询。

提前道具。

【问题讨论】:

    标签: html css flexbox css-grid


    【解决方案1】:

    下面的代码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;
    }
    <div id="structure-content">
        <main>content goes here</main>
        <aside>aside content</aside>
    </div>

    【讨论】:

    • 感谢您的回答。正如我上面提到的,我需要列的宽度不同。不过,您的代码确实给了我一些想法。干杯。
    【解决方案2】:

    使用 CSS Grid,您可以使 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;
    }
    <div id="structure-content">
      <main>content goes here</main>
      <aside>aside content</aside>
    </div>

    解决方案

    使用 CSS Grid,我想说您可以使用 媒体查询。无论如何,flexbox 在这里可以很好地工作:

    • 使用包装弹性框
    • 为每个asidemain 保留一个min-width,并将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;
    }
    <div id="structure-content">
      <main>content goes here</main>
      <aside>aside content</aside>
    </div>

    【讨论】:

    • 感谢您的代码。看来我几乎可以让它全部工作,并且可能我会通过更多的修补来解决它。实际上,您的代码 sn-p 验证了我对所采用方法的一些想法。感谢您的时间和洞察力。
    猜你喜欢
    • 1970-01-01
    • 2018-09-16
    • 2016-07-31
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    • 2018-04-28
    • 2019-08-24
    相关资源
    最近更新 更多