使用CSS Grid,如何在同一列上有多个元素,跨越多行?

时间:2018-03-13 22:25:27

标签: css css-grid

我是以下HTML和CSS(.type-a部分),它使用的是CSS网格。

you can see the CodePen clicking here

我需要的是让所有.col1类的元素在第一列上正确对齐 - 同时使.col2跨越整行。

更改HTML不是一个选项(我知道通过更改HTML很容易解决这个问题。)

我们永远不会确切地知道.col1会有多少行,我确实希望避免创建1000行以使其正常工作(就像您在.type-b上看到的那样)。

.container {
  display: grid;
  grid-auto-columns: 50%;
  grid-auto-flow: dense;
  /* Decorative */
  color: #ffffff;
  text-align: center;
}

.col1 {
  grid-column: 1;
}

.col2 {
  grid-column: 2;
}

// Type B
.type-b>.col2 {
  grid-row: 1 / 100;
}

// Decorative Styles
.divider {
  height: 1px;
  background: #B0BEC5;
  margin: 30px;
}

.content-a {
  background: #5C6BC0;
}

.content-b {
  background: #7E57C2;
}

.content-c {
  background: #AB47BC;
}

.content-d {
  background: #FFA726;
}
<h3>Type A</h3>
<div class="container type-a">
  <div class="col1 content-a">Content A</div>
  <div class="col1 content-b">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ac auctor erat. Phasellus porta nec dolor ut egestas. Praesent pretium elit vel risus iaculis, vel condimentum lorem volutpat. Nunc placerat massa ac venenatis dictum. Donec ullamcorper, magna
    efficitur laoreet euismod, arcu neque aliquam purus, sed ornare dolor sem sed est.
  </div>
  <div class="col1 content-c">Content C</div>
  <div class="col2 content-d">
    <img src="https://picsum.photos/200/300">
  </div>
</div>

<div class="divider"></div>

<h3>Type B (What I want)</h3>
<div class="container type-b">
  <div class="col1 content-a">Content A</div>
  <div class="col1 content-b">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ac auctor erat. Phasellus porta nec dolor ut egestas. Praesent pretium elit vel risus iaculis, vel condimentum lorem volutpat. Nunc placerat massa ac venenatis dictum. Donec ullamcorper, magna
    efficitur laoreet euismod, arcu neque aliquam purus, sed ornare dolor sem sed est.
  </div>
  <div class="col1 content-c">Content C</div>
  <div class="col2 content-d">
    <img src="https://picsum.photos/200/300">
  </div>
</div>

1 个答案:

答案 0 :(得分:0)

您似乎可以设置

.col2 { 
   grid-row-end: span 99999;
}

,它将跨越网格中的所有行,除非您的行数超过99999。这不是理想的方法,但似乎在Firefox和Chrome中可以正常工作!

此处的Codepen:https://codepen.io/anon/pen/qgmpvv