【问题标题】:CSS Force odd number of elements per lineCSS强制每行奇数个元素
【发布时间】:2017-08-25 18:18:11
【问题描述】:

我有一堆内联块元素。奇数和偶数元素的样式不同,因此我希望它们仅在每行奇数个元素后才换行,以在调整屏幕大小时保留网格图案。如果重要的话,所有元素的大小都相同。

.thing{
    display:inline-block;
    height:100px;
    width:100px;
    margin:5px;
}
.thing:nth-child(odd){
    background-color: #999;
    border-radius: 0 20px;
}
.thing:nth-child(even){
    background-color: #ccc;
    border-radius: 20px 0;
}
/* something that will only allow line breaks after 1st or 3rd or 5th etc element  */

有没有办法优雅地做到这一点?我想理论上可以为每个“案例”做一堆媒体查询块并使用 :nth-child():after 强制换行,但我想避免这种情况。

【问题讨论】:

    标签: css line-breaks


    【解决方案1】:

    您可以使用 css 网格每行显示 3 个(或 5 个或任何需要的)。

    .wrap-things {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        grid-gap: 10px;
    }
    .thing {
        height:100px;
        width:100px;
        margin: auto;
    }
    .thing:nth-child(odd){
        background-color: #999;
        border-radius: 0 20px;
    }
    .thing:nth-child(even){
        background-color: #ccc;
        border-radius: 20px 0;
    }
    <div class="wrap-things">
      <div class="thing"></div>
      <div class="thing"></div>
      <div class="thing"></div>
      <div class="thing"></div>
      <div class="thing"></div>
      <div class="thing"></div>
      <div class="thing"></div>
      <div class="thing"></div>
    </div>

    【讨论】:

    • 如果我尝试每行有偶数个元素,那会起作用,但我会选择奇数。另外,我正在尝试尽可能避免语义上无意义的容器等,以免混淆屏幕阅读器等东西。
    • 为了奇数,您可以在 .wrap-things 中包含三个 .thing。这仍然没有改变会有许多无意义的容器的事实。除了创建大量断点之外,这是我能看到的让它工作的唯一方法。很抱歉,它没有更多帮助。您可以尝试网格规范,但浏览器支持还不是 100%。 caniuse.com/#search=grid
    • @Rose Liu:屏幕阅读器应该足够聪明,能够理解语义上无意义的元素就是:无意义。
    • @JRoss 在.wrap-thing 中包装三个东西不会强制它连续显示奇数个元素。例如,它可以连续放置六个。
    猜你喜欢
    • 2011-05-11
    • 2012-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    • 2021-10-17
    • 1970-01-01
    • 2021-02-19
    相关资源
    最近更新 更多