skip to Main Content

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>

3

Answers


  1. You’re close – use nth-child 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>
    Login or Signup to reply.
  2. .questionsAndAnswers {
         display: grid;
         grid-template-columns: 1fr 1fr;
         grid-gap: 24px;
         font-size: 12px;
         font-family: "sans-serif";
         border: 1px solid red;
    }
     .questionsAndAnswers p:nth-child(1){
         grid-row: 1;
         grid-column: 1;
    }
     .questionsAndAnswers p:nth-child(2){
         grid-row: 1;
         grid-column: 2;
    }
     .questionsAndAnswers p:nth-child(3){
         grid-row: 2;
         grid-column: 1;
    }
     .questionsAndAnswers p:nth-child(4){
         grid-row: 2;
         grid-column: 2;
    }
    
    Login or Signup to reply.
  3. .questionsAndAnswers

    {

     display: grid;
     grid-template-columns: 1fr 1fr;
     grid-gap: 24px;
     font-size: 12px;
     font-family: "sans-serif";
     border: 1px solid red;
    

    }

    .questionsAndAnswers p:nth-child(1)

    {

     grid-row: 1;
     grid-column: 1;
    

    }

    .questionsAndAnswers p:nth-child(2)

    {

     grid-row: 1;
     grid-column: 2;
    

    }

    .questionsAndAnswers p:nth-child(3)

    {

     grid-row: 2;
     grid-column: 1;
    

    }

    .questionsAndAnswers p:nth-child(4)

    {

     grid-row: 2;
     grid-column: 2;
    

    }

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search