如何使用 CSS nth-child(odd) nth-child(even) 来对齐 CSS 网格中的列?

问题描述 投票:0回答:3

我有一个 CSS 网格。我想使用

nth-child
odd
even
选择器将项目推到网格的每个垂直边缘 - 它应该看起来像:

.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>

html css css-grid
3个回答
4
投票

你很接近 - 在子元素上使用

nth-child
伪选择器
<p>
代替,并使用
justify-self
代替
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>


0
投票

.问题和答案

{

 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;

}


-1
投票
.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;
}
© www.soinside.com 2019 - 2024. All rights reserved.