CSS Grid设置grid-auto-rows后隐式行高度不一致问题
CSS Grid 布局隐式行高度不一致问题
- 实现了一个初始为两列等宽的CSS Grid布局,代码见下文
- 页面缩放过程中,布局自动生成的隐式行高度不一致,即使设置
grid-auto-rows属性后问题仍然存在 - 已尝试将
grid-auto-rows属性值修改为auto,问题未解决
HTML(React JSX)
const Landing = () => { return ( <section id="home" className="landing"> <div className="landing__content"> <div> <h3 className="subheading-default"></h3> <h1 className="primary spancolor-red"></h1> </div> </div> <figure className="landing__imagecontainer"> <img src={require("../../assets/images/landing.jpeg")} alt="" className="landing__image" /> </figure> </section> ); };
SCSS(原始代码)
.landing { height: 96vh; display: grid; grid-template-columns: repeat(auto-fit, minmax(373.5px, 1fr)); grid-auto-rows: 1fr; &__content { display: flex; flex-direction: column; justify-content: center; align-items: center; } &__image { height: 100%; width: 100%; object-fit: cover; } }
修复方案
问题出在两个容易忽略的细节:
- Grid布局中
1fr的默认计算逻辑是minmax(auto, 1fr),auto优先级高于比例分配,会优先适配子元素的固有内容尺寸,不会强制行高严格均分,因此写的grid-auto-rows: 1fr并不会实现等高效果 - 图片外层的
<figure>标签自带浏览器默认margin,且没有设置撑满网格单元的尺寸规则,图片的高度计算基准偏移,会进一步拉大不同行的高度差
直接调整SCSS代码即可解决:
.landing { height: 96vh; display: grid; grid-template-columns: repeat(auto-fit, minmax(373.5px, 1fr)); // 替换原有grid-auto-rows配置,强制行高按比例均分 grid-auto-rows: minmax(0, 1fr); &__content { display: flex; flex-direction: column; justify-content: center; align-items: center; } // 新增图片容器样式,清除默认边距、撑满整个网格单元 &__imagecontainer { margin: 0; height: 100%; width: 100%; } &__image { height: 100%; width: 100%; object-fit: cover; } }
调整后无论页面如何缩放、布局折为几行,所有隐式行都会严格均分容器高度,不会出现高度不一致的问题。
内容的提问来源于stack exchange,提问作者Krish
相关产品推荐
相关产品推荐

