Home > other >  Change order of items in CSS Grid
Change order of items in CSS Grid

Time:09-23

I have a css-grid that is almost working the way that I want, but I cant figure out how to change the order of items in a specific way.

The html of the items is laid out in a “1, 2, 3, 4,…10” order. But at smaller screen sizes, I’d like the visual order to be “1, 2, 4, 3,5,6…10”

Ideally, from an accessibility POV, my guess is that this would be better to do in the DOM - but thats beyond my current skill level - and this is for a portfolio site aimed at sighted users, so I’m okay with just changing the visual order of the grid in the CSS until I figure out the DOM stuff.

I’m looking for CSS feedback, but am open to hearing how to change the DOM

enter image description here

* {
    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>

CodePudding user response:

The only addition that is needed to the given code is to set the first two elements to order 1, the featured element to order 2 and all the others to order 3.

CSS grid will place the third li alongside the two with order 1 when there is room otherwise it will go below the featured 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>

CodePudding user response:

grid-template-areas can be useful for your case. https://www.w3schools.com/css/tryit.asp?filename=trycss_grid_layout_named

  • Related