我一直在玩弄 CSS 网格并制作了一个 <section>
将图像放在文本旁边并反转 <section>
中的列顺序以下。
当缩小屏幕时,我希望图像始终显示在文本上方。
我现在可以正常工作了,但是 CSS 看起来真的很困惑,我一直在努力缩短它的长度,我认为这应该可以通过 CSS Grid 实现。
.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>
最佳答案
您也可以使用普通的老式 float 或非常灵活的 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>
关于html - 如何使反转列的 CSS 网格样式不那么困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47859976/