maruf228
maruf228

Reputation: 133

CSS Grid place items from right to left

I am working on a web application that has a member list. The quantity of member will come dynamically from the server. I want to show each member's info in a grid of four columns. Is it possible to dynamically place each item from right to left using Css Grid?

Upvotes: 12

Views: 13392

Answers (2)

squarecandy
squarecandy

Reputation: 5107

Two possible good solutions for this that avoid the language-centric direction:

  1. Use flex instead of grid with flex-direction: row-reverse;
  2. If you know for sure the number of columns you can do something like this:

.container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-auto-flow: dense;

  gap: 1em;
}

.container div:nth-child(4n + 1) {
  grid-column: 4;
}

.container div:nth-child(4n + 2) {
  grid-column: 3;
}

.container div:nth-child(4n + 3) {
  grid-column: 2;
}

.container div:nth-child(4n + 4) {
  grid-column: 1;
}

/* just for demo */
.container div {
  border: 1px solid red;
  padding: 5px;
  text-align: center;
}
<div class="container">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  <div>8</div>
  <div>9</div>
  <div>10</div>
  <div>11</div>
  <div>12</div>
</div>

Upvotes: 0

Sa1m0n
Sa1m0n

Reputation: 806

You should use direction property:

.container
{
  display: grid;
  grid-template-columns: 25vw 25vw 25vw 25vw;
  grid-template-rows: 100vh; /* Your number of rows */
  grid-auto-flow: column;
  direction: rtl;
}

Upvotes: 23

Related Questions