【问题标题】:Change order of items in CSS Grid更改 CSS Grid 中项目的顺序
【发布时间】:2021-09-22 19:41:10
【问题描述】:

我有一个 css-grid 几乎可以按照我想要的方式工作,但我不知道如何以特定方式更改项目的顺序。

项目的 html 以“1、2、3、4、…10”的顺序排列。但在较小的屏幕尺寸下,我希望视觉顺序为“1、2、4、3、5、6…10”

理想情况下,从可访问性 POV 来看,我的猜测是在 DOM 中这样做会更好 - 但这超出了我目前的技能水平 - 这是针对有视力的用户的投资组合网站,所以我同意只是改变 CSS 中网格的视觉顺序,直到我弄清楚 DOM 的东西。

我正在寻找 CSS 反馈,但愿意听取如何更改 DOM

* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}
body {
    font-family: Arial,  Geneva,  Helvetica,  sans-serif;
    color: #515C62;
}
ul {
    display: grid;
    grid-template-columns: repeat(auto-fill,  minmax(max(200px,  100% / 3),  1fr));
    grid-auto-flow: dense;
}
li {
    background: #CACAC7;
    padding: 5px;
    height: 50px;
    margin: 10px;
    list-style-type: none;
    color: white;
    font-weight: bold;
    font-size: 2em;
    text-align: center;
}
#feature {
    background-color: #FF5916;
    color: white;
    grid-column: 1 / -1;
}
<body>
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li id="feature">4 (feature)</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
    <li>8</li>
  </ul>
</body>

【问题讨论】:

    标签: javascript html css grid css-grid


    【解决方案1】:

    对给定代码唯一需要添加的是将前两个元素设置为顺序 1,将特征元素设置为顺序 2,将所有其他元素设置为顺序 3。

    当有空间时,CSS 网格会将第三个 li 放置在顺序为 1 的两个 li 旁边,否则它将低于特色 li。

    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }
    
    body {
      font-family: Arial, Geneva, Helvetica, sans-serif;
      color: #515C62;
    }
    
    ul {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(max(200px, 100% / 3), 1fr));
      grid-auto-flow: dense;
    }
    
    li {
      background: #CACAC7;
      padding: 5px;
      height: 50px;
      margin: 10px;
      list-style-type: none;
      color: white;
      font-weight: bold;
      font-size: 2em;
      text-align: center;
      order: 3;
    }
    
    #feature {
      background-color: #FF5916;
      color: white;
      grid-column: 1 / -1;
      order: 2;
    }
    
    li:nth-child(1),
    li:nth-child(2) {
      order: 1;
    }
    <body>
      <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li id="feature">4 (feature)</li>
        <li>5</li>
        <li>6</li>
        <li>7</li>
        <li>8</li>
      </ul>
    </body>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-20
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多