Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

html - CSS Grid unwanted column added automatically

Trying to group items in two separate line by CSS Grid using different class names. It works fine until in "red" group have no more elements then predefined rows (this case 3).

Can I somehow put the 4th "red" element in new row?

If there is only 3 "red" element, everything works fine.

ul {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}

.blue {
  background-color: blue;
}

.red {
  background-color: red;
  grid-row-start: 5;
}
<ul>
  <li class="blue">
    <h2>1</h2>
  </li>
  <li class="red">
    <h2>2</h2>
  </li>
  <li class="blue">
    <h2>3</h2>
  </li>
  <li class="blue">
    <h2>4</h2>
  </li>
  <li class="red">
    <h2>5</h2>
  </li>
  <li class="red">
    <h2>6</h2>
  </li>
  <!-- If you delete this (or any other "red") "li" element then it's working fine -->
  <li class="red">
    <h2>7</h2>
  </li>
  <li class="blue">
    <h2>8</h2>
  </li>
</ul>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are specifying all the red elements into the fifth row by using grid-row-start: 5. Yes, the red elements are placed to the fifth row, and that is not immediately visible as you haven't specified an explicit row definition (say using grid-template-rows).


Implicit Rows

You can define the implicit row definition using something like grid-auto-rows: 50px and see that the red element are actually in the fifth row:

ul {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-auto-rows: 50px; /* specify row height */
  list-style: none; /* remove bullets */
  padding: 0; /* remove default ul padding */
}

.blue {
  background-color: blue;
}

.red {
  background-color: red;
  grid-row-start: 5;
}

li {
  border: 1px solid #bbb; /* border for illustration */
}
<ul>
  <li class="blue">
    <h2>1</h2>
  </li>
  <li class="red">
    <h2>2</h2>
  </li>
  <li class="blue">
    <h2>3</h2>
  </li>
  <li class="blue">
    <h2>4</h2>
  </li>
  <li class="red">
    <h2>5</h2>
  </li>
  <li class="red">
    <h2>6</h2>
  </li>
  <!-- If you delete this (or any other "red") "li" element then it's working fine -->
  <li class="red">
    <h2>7</h2>
  </li>
  <li class="blue">
    <h2>8</h2>
  </li>
</ul>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...