如何在CSS Grid列中放置宽度适配列宽的fixed固定定位元素
实现方案
核心修改点
- 给中间列容器
#two添加position: relative属性,作为固定元素的位置参照 - 调整固定元素
#shape的样式:- 移除原有的
width: 100%配置 - 新增
width: inherit继承父网格列的宽度 - 新增
left: inherit、right: inherit继承父网格列的左右偏移量
- 移除原有的
原理解释
position: fixed默认相对于浏览器视口定位,直接设置width: 100%会取整个视口宽度,和所在网格列无关。通过继承相对定位的父容器的宽度和左右位置,固定元素的尺寸和水平位置会始终和父网格列完全对齐,后续修改网格列配置时不需要调整固定元素的样式,可自动适配。
修改后完整CSS代码
* { margin: 0; padding: 0; } html, body { width: 100%; height: 100%; } main { display: grid; grid-template-columns: repeat(6, 1fr); } section { height: 100px; width: 100%; } #one { grid-column-start: 1; grid-column-end: 2; } #two { grid-column-start: 2; grid-column-end: 6; position: relative; /* 新增属性 */ } #three { grid-column-start: 6; grid-column-end: 7; } #shape { top: 0; position: fixed; background-color: red; height: 200px; opacity: 0.9; width: inherit; /* 替换原有width:100% */ left: inherit; /* 新增属性 */ right: inherit; /* 新增属性 */ }
内容的提问来源于stack exchange,提问作者Anna_B
相关产品推荐
相关产品推荐

