下面的代码片段使用CSS Grid来增加宽容器的列数.对于窄容器(例如,取消注释宽度:80vw或调整示例大小),它会添加隐式行(grid-template-rows属性中只有2个是显式的).如何只保留2行,使2-by-n网格“溢出”的网格项隐藏?
.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>
解决方法
您可以使用grid-auto-rows将自动生成的行的高度设置为0px:0;并使用overflow-y隐藏它们:隐藏.演示:
.wrapper { border: 2px solid #f76707; background-color: #fff4e6; display: grid; grid-template-columns: repeat(auto-fill,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>