如何使反转列的 CSS 网格样式不那么混乱

How to make a CSS Grid style that reverses columns less cluttered

我一直在研究 CSS 网格并制作了一个 <section> 将图像放在文本旁边并反转下面 <section> 中的列顺序。

缩小屏幕时,我希望图像始终显示在文本上方。

我现在可以正常工作了,但是 CSS 看起来真的很乱,我一直在努力让它更短,我认为 CSS 网格应该可以做到这一点。

.color:nth-child(odd) {
  background-color: red;
}

.color:nth-child(even) {
  background-color: green;
}

section {
  background: black;
  padding: 20px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-auto-flow: dense;
}

.content {
  grid-column: 1 / 2;
  text-align: center;
}

.content:nth-child(2) {
  grid-column: 2 / 3;
}

.reverse>.content {
  grid-column: 2 / 3;
}

.reverse>.content:nth-child(2) {
  grid-column: 1 / 2;
}

@media(max-width: 768px) {
  .content {
    grid-column: 1 / 3;
  }
  .content:nth-child(2) {
    grid-column: 1 / 3;
  }
  .reverse>.content {
    grid-column: 1 / 3;
  }
  .reverse>.content:nth-child(2) {
    grid-column: 1 / 3;
  }
}
<section>
  <div class="content color">
    <p>
      Image
    </p>
  </div>

  <div class="content color">
    <p>Text</p>
  </div>

</section>
<section class="reverse">
  <div class="content color">
    <p>Image</p>
  </div>

  <div class="content color">
    <p>Text</p>
  </div>
</section>

我不完全确定这就是您想要的,但您可以用逗号分隔选择器来分组规则。

.color:nth-child(odd) {
  background-color: red;
}

.color:nth-child(even) {
  background-color: green;
}

section {
  background: black;
  padding: 20px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-auto-flow: dense;
}

.content,
.reverse>.content:nth-child(2){
  grid-column: 1 / 2;  
}

.content {text-align: center;}

.content:nth-child(2),
.reverse>.content  {
  grid-column: 2 / 3;
}


.reverse>.content:nth-child(2) {
  grid-column: 1 / 2;
}

@media(max-width: 768px) {
  .content,
  .content:nth-child(2),
  .reverse>.content,
  .reverse>.content:nth-child(2){
    grid-column: 1 / 3;
  }
}
<section>
  <div class="content color">
    <p>
      Image
    </p>
  </div>

  <div class="content color">
    <p>Text</p>
  </div>

</section>
<section class="reverse">
  <div class="content color">
    <p>Image</p>
  </div>

  <div class="content color">
    <p>Text</p>
  </div>
</section>

您也可以使用普通的旧浮动或非常灵活的 flexbox,但如今似乎必须了解网格。 还有更多选项,这只是一个使用 order.

的选项

.color:nth-child(odd) {
  background-color: red;
}

.color:nth-child(even) {
  background-color: green;
}

section {
  background: black;
  padding: 20px;
  display: grid;
  grid-template-columns: 1fr;
  grid-auto-flow: dense;
}

@media(min-width: 768px) {
  section {
    grid-template-columns: 1fr 1fr;
  }
  .reverse .color:first-child {
    order: 2;
  }
}
<section>
  <div class="content color">
    <p>
      Image
    </p>
  </div>

  <div class="content color">
    <p>Text</p>
  </div>

</section>
<section class="reverse">
  <div class="content color">
    <p>Image</p>
  </div>

  <div class="content color">
    <p>Text</p>
  </div>
</section>