【CSS】Grid 的 auto-fill 和 auto-fit 内容自适应
CSS Grid 的 auto-fill 和 auto-fit
/* 父元素 */
.grid {display: grid;/* 定义「网格容器」里有多少列,以及每列的宽度 *//* repeat 是个「重复函数」,表示后面的模式会被重复多次 *//* auto-fit 是一个特殊值,自动根据容器宽度,能放下几个就放几个,每列都用后面的规则 *//* minmax 也是一个函数,每列最小 200px,最大可以占 1fr(剩余空间的平分) */grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}/* 子元素 */
.item {height: 200px;background-color: rgb(141, 141, 255);border-radius: 10px;
}
auto-fill 和 auto-fit 区别
auto-fill:尽可能多地填充列,即使没有内容也会“占位”;
auto-fit:自动适应内容,能合并多余空列,不占位;
auto-fill 和 auto-fit 适用场景
希望每行有多少内容就撑多宽,用 auto-fit;(如:卡片式布局、相册等)
希望固定列数,有占位,用auto-fill;(如:表格、日历等)