Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

The snippet below uses CSS Grid to increase the number of columns for wide containers. For narrow containers (e.g. uncomment width: 80vw or resize the example), it adds implicit rows (only 2 are explicit in the grid-template-rows property). How can I maintain only 2 rows, making the grid items that "overflow" the 2-by-n grid hidden?

.wrapper {
  border: 2px solid #f76707;
  background-color: #fff4e6;
  display: grid;
  /* width: 80vw; */
  grid-template-columns: repeat(auto-fill, 200px);
  grid-template-rows: repeat(2, 1fr);
}

.wrapper > div {
  border: 2px solid #ffa94d;
  border-radius: 5px;
  background-color: #ffd8a8;
  padding: 1em;
  color: #d9480f;
}
<div class="wrapper">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
  <div>Four</div>
  <div>Five</div>
</div>
See Question&Answers more detail:os

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

1 Answer

You can set height of auto generated row to 0px using grid-auto-rows: 0; and hide them using overflow-y: hidden. Demo:

.wrapper {
  border: 2px solid #f76707;
  background-color: #fff4e6;
  display: grid;
  grid-template-columns: repeat(auto-fill, 200px);
  grid-template-rows: repeat(2, 1fr);
  grid-auto-rows: 0; /* set height to 0 for autogenerated grid rows */
  overflow-y: hidden; /* hide grid items that overflow */
}

.wrapper > div {
  border: 2px solid #ffa94d;
  border-radius: 5px;
  background-color: #ffd8a8;
  padding: 1em;
  color: #d9480f;
}
<div class="wrapper">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
  <div>Four</div>
  <div>Five</div>
  <div>Six</div>
  <div>Seven</div>
  <div>Eight</div>
  <div>Nine</div>
  <div>Ten</div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...