Search code examples
htmlcsscss-grid

How can I use CSS nth-child(odd) nth-child(even) to justify columns in a CSS grid?


I have a CSS grid. I would like to use the nth-child odd and even selectors to make items be pushed up against each vertical edge of the grid - it should look like:

enter image description here

.questionsAndAnswers {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 24px;
  font-size: 12px;
  font-family: "sans-serif";
  justify-items: end;
  border: 1px solid red;
}

.questionsAndAnswers:nth-child(odd){
  justify-items: start;
}
<div class="questionsAndAnswers">
  <p>
    one
  </p>
  <p>
    two
  </p>
  <p>
    three
  </p>
  <p>
    four
  </p>
</div>


Solution

  • You're close - use nth-child / nth-type pseudo selector on the child <p>-elements instead, and use justify-self instead of justify-items.

    .questionsAndAnswers {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      grid-gap: 24px;
      font-size: 12px;
      font-family: "sans-serif";
      border: 1px solid red;
    }
    
    .questionsAndAnswers p:nth-of-type(even){
      justify-self: end;
    }
    
    .questionsAndAnswers p:nth-of-type(odd){
      justify-self: start;
    }
    <div class="questionsAndAnswers">
      <p>
        one
      </p>
      <p>
        two
      </p>
      <p>
        three
      </p>
      <p>
        four
      </p>
    </div>