Search code examples
htmlcssmedia-queriescss-grid

How to make a CSS Grid style that reverses columns less cluttered


I have been playing around with CSS Grid and made a <section> that puts a image next to a text and reverses the column order in the <section> below.

When making the screen smaller I want the images to always display above the text.

I have this working now but the CSS looks really cluttered, I have been trying to make it shorter which I think should be possible with CSS Grid.

.color:nth-child(odd) {
  background-color: red;
}

.color:nth-child(even) {
  background-color: green;
}

section {
  background: black;
  padding: 20px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-auto-flow: dense;
}

.content {
  grid-column: 1 / 2;
  text-align: center;
}

.content:nth-child(2) {
  grid-column: 2 / 3;
}

.reverse>.content {
  grid-column: 2 / 3;
}

.reverse>.content:nth-child(2) {
  grid-column: 1 / 2;
}

@media(max-width: 768px) {
  .content {
    grid-column: 1 / 3;
  }
  .content:nth-child(2) {
    grid-column: 1 / 3;
  }
  .reverse>.content {
    grid-column: 1 / 3;
  }
  .reverse>.content:nth-child(2) {
    grid-column: 1 / 3;
  }
}
<section>
  <div class="content color">
    <p>
      Image
    </p>
  </div>

  <div class="content color">
    <p>Text</p>
  </div>

</section>
<section class="reverse">
  <div class="content color">
    <p>Image</p>
  </div>

  <div class="content color">
    <p>Text</p>
  </div>
</section>


Solution

  • You could also use a plain old float or the very flexible flexbox, but knowing grid seems to be a must nowadays. There are a few more options, this is just one using order.

    .color:nth-child(odd) {
      background-color: red;
    }
    
    .color:nth-child(even) {
      background-color: green;
    }
    
    section {
      background: black;
      padding: 20px;
      display: grid;
      grid-template-columns: 1fr;
      grid-auto-flow: dense;
    }
    
    @media(min-width: 768px) {
      section {
        grid-template-columns: 1fr 1fr;
      }
      .reverse .color:first-child {
        order: 2;
      }
    }
    <section>
      <div class="content color">
        <p>
          Image
        </p>
      </div>
    
      <div class="content color">
        <p>Text</p>
      </div>
    
    </section>
    <section class="reverse">
      <div class="content color">
        <p>Image</p>
      </div>
    
      <div class="content color">
        <p>Text</p>
      </div>
    </section>