如何解决CSS网格-将两行与不同列数对齐
我有一个与CSS网格有关的问题。假设我有2行:
第一行:
<div class="first-row">
<div>
Col 1
</div>
<div>
Col 2
</div>
<div>
Col 3
</div>
<div>
Col 4
</div>
</div>
第二行:
<div class="second-row">
<div>
<span>Under Col 1</span>
</div>
<div>
<span>Under Col 2</span>
</div>
<div class"SPLIT-THIS">
<span>Under Col 3</span>
<span>Under Col 4</span>
</div>
</div>
如何拆分第二行中的最后一个div
元素,以使第一行中的内容与第二行中的内容完全对齐(就像它们在结构上是相同的行一样)。
我使用的CCS:
.first-row {
grid-template-columns: repeat(4,1fr);
grid-gap: 20px;
align-items: center;
justify-content: center;
text-align: center;
}
.second-row {
grid-template-columns: repeat(3,1fr);
grid-gap: 20px;
align-items: center;
justify-content: center;
text-align: center;
}
解决方法
我将实现所谓的“子网格”或“网格级别2”。
虽然在CSS中使用“ display:grid;”定义了同时包含两个初始行的容器,但使用单独的“ display:grid;”定义了“ SPLIT-THIS”。 然后,使用“ grid-template-rows:50%,50%;”同样适用于“ SPLIT-THIS”。
,- 第一种选择/方法: 两个容器都需要具有相同数量的列和相同大小才能在视觉上进行匹配。
然后,split元素需要跨越2列,并且本身就是网格容器。
.first-row {
display: grid;
grid-template-columns: repeat(4,1fr);
align-items: center;
justify-content: center;
text-align: center;
}
.second-row {
display: grid;
grid-template-columns: repeat(4,1fr);
align-items: center;
justify-content: center;
text-align: center;
}
.SPLIT-THIS {
grid-column: span 2;
display: grid;
grid-template-columns: repeat(2,1fr);
}
div,.SPLIT-THIS span {
box-shadow: inset 0 0 0 1px
}
<div class="first-row">
<div>
Col 1
</div>
<div>
Col 2
</div>
<div>
Col 3
</div>
<div>
Col 4
</div>
</div>
<div class="second-row">
<div>
<span>Under Col 1</span>
</div>
<div>
<span>Under Col 2</span>
</div>
<div class="SPLIT-THIS">
<span>Under Col 3</span>
<span>Under Col </span>
</div>
</div>
- 如果您只希望3列,其他选项是重新定义网格列模板
.first-row {
display:grid;
grid-template-columns: repeat(4,1fr);
align-items: center;
justify-content: center;
text-align: center;
}
.second-row {
display:grid;
grid-template-columns: 1fr 1fr 2fr ;
align-items: center;
justify-content: center;
text-align: center;
}
.SPLIT-THIS{
display:grid;
grid-template-columns:repeat(2,1fr);
}
div,.SPLIT-THIS span {box-shadow:inset 0 0 0 1px}
<div class="first-row">
<div>
Col 1
</div>
<div>
Col 2
</div>
<div>
Col 3
</div>
<div>
Col 4
</div>
</div>
<div class="second-row">
<div>
<span>Under Col 1</span>
</div>
<div>
<span>Under Col 2</span>
</div>
<div class="SPLIT-THIS">
<span>Under Col 3</span>
<span>Under Col </span>
</div>
</div>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。