如何制作一个CSS网格样式来反转不那么混乱的列

时间:2017-12-17 22:12:57

标签: html css media-queries css-grid

我一直在玩CSS Grid并制作了一个<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 { 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; } }中的列顺序。

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

我现在有这个工作,但CSS看起来很混乱,我一直试图缩短它,我认为应该可以使用CSS Grid。

<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>
{{1}}

2 个答案:

答案 0 :(得分:0)

我不完全确定这是你所追求的,但你可以用逗号分隔选择器来分组规则。

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

答案 1 :(得分:0)

You could also use a plain old float or the very flexible flexbox, but knowing grid seems to be a must nowadays. There are a few more options, this is just one using <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>SetTimeout</title> </head> <body> <span class="element">hello</span> </body> </html>.

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