如何使用CSS第n个子元素(奇数)和第n个子元素(偶数)来对齐CSS网格中的列?

u0njafvf  于 2023-04-23  发布在  其他
关注(0)|答案(3)|浏览(129)

我有一个CSS网格。我想使用nth-childoddeven选择器来使项目被推到网格的每个垂直边缘-它应该看起来像:

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

qgzx9mmu1#

你接近了-在子<p>-元素上使用nth-child伪选择器,并使用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>
30byixjq

30byixjq2#

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

}

gmxoilav

gmxoilav3#

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

相关问题