Search code examples
javascripthtmlcssreactjstailwind-css

How to reverse grid layout to be from right to left in CSS


I start doing some project to improve my skill, but I face an annoying issue, my simple project is fetching data from API and render it to the DOM, but the data is in Arabic and its start from right to left, but the grid layout starts from left so the word it's not in the correct order here some images of my project:

enter image description here

enter image description here

enter image description here


Solution

  • In your case, because you're using an rtl language, applying dir="rtl" should do it:

    <div id="Chapter" className="grid grid-cols-3" dir="rtl">
     ...
    </div>
    

    See it working.


    Note: to achieve this without changing the reading direction, you could use:

    #Chapter {
      display: flex;
      flex-wrap: wrap;
      flex-direction: row-reverse;
    }
    

    The concept of row-reverse doesn't exist in grid-auto-flow accepted values (which would be the equivalent of flex-direction for grids).

    This means the only way to do it for a display: grid element would be to specify the position of each element in the grid, which could be achieved using the following SCSS mixin:

    @mixin reverse-grid($cols) {
      display: grid;
      grid-template-columns: repeat($cols, 1fr);
      grid-auto-flow: row dense;
      @for $col from 1 through $cols {
        > *:nth-child(#{$cols}n + #{$col}) {
          grid-column: (#{$cols + 1 - $col});
        }
      }
    }
    

    See it working.

    The above mixin compiles

    .reverse-grid {
      @include reverse-grid(3);
    }
    

    into

    .reverse-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      grid-auto-flow: row dense;
    }
    .reverse-grid > *:nth-child(3n + 1) {
      grid-column: 3;
    }
    .reverse-grid > *:nth-child(3n + 2) {
      grid-column: 2;
    }
    .reverse-grid > *:nth-child(3n + 3) {
      grid-column: 1;
    }
    

    and it can be used with any number of columns.