You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 23:15:06