我有一个 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>
你很接近 - 在子元素上使用
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>
.问题和答案
{
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;
}
.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;
}