CSS网格:如何将同一网格区域的元素排队



我的目标是将CSS网格布局用于两列砌体布局。给有孩子的元素:

<section>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</section>

将孩子们交替地分类为列。我的想法是有两个网格区域leftright,并告诉孩子们分开:

section {
  display: grid;
  grid-template-areas: "left right";
}
div:nth-child(odd) {
  grid-area: left;
}
div:nth-child(even) {
  grid-area: right;
}

这是一个jsbin,说明了我当前状态:https://jsbin.com/zaduruv/edit?html.css,output

不幸的是,这些元素的反应与 position:absolute设置完全相同。也就是说,他们都挤向顶部并互相重叠。

CSS网格布局属性是否有可能使孩子们在列中排队,就像他们正常使用position: static一样?

你不能。由于元素可以在CSS网格中相互重叠,因此甚至不会尝试对齐它们。顾名思义,它是网格,而不是列布局。

一个更好的解决方案是使用CSS多列布局,如下面的摘要。

多列布局的唯一问题是,它是垂直分布而不是水平分布的,因此您可以得到:

1 42 53 6

而不是这样:

1 23 45 6

section {
    -webkit-column-count: 2; /* Chrome, Safari, Opera */
    -moz-column-count: 2; /* Firefox */
    column-count: 2;
    -webkit-column-gap: 0;
    -moz-column-gap: 0;
    column-gap: 0;
    width: 500px;
    background-color: #e0e0e0;
}
div {
  width: 250px;
  display: inline-block;
}
div:nth-child(1) {
  background-color: #c1c0c1;
  height: 100px;
}
div:nth-child(2) {
  background-color: #fedbc1;
  height: 50px;
}
div:nth-child(3) {
  background-color: #dec34a;
  height: 130px;
}
div:nth-child(4) {
  background-color: #ce3294;
  height: 110px;
}
div:nth-child(5) {
  background-color: #99deac;
  height: 80px;
}
div:nth-child(6) {
  background-color: #aade34;
  height: 190px;
}
<section>
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
</section>

您必须抛弃此网格区域,并使用网格柱启动。否则,一切都将放入同一区域。https://jsbin.com/peqiwodoba/edit?html.css,output

div:nth-child(odd) {
}
div:nth-child(even) {
  grid-column-start: 2;
}

最新更新