【css】如何让 fixed 元素具有父节点同样的宽度?

有不少人说使用inherit ,当然这是没用的。

还有不少人认为父级元素使用relative,子元素(fixed)的宽度设为100%就可以,这也是错误的。使用relative的观点是把absolutefixed认为是一样的,其实不是。区别在于:

  • absolute定位是相对于最近的relative
  • fixed定位是相对于视口(viewport)!

有效的方法是通过javascript获取父级元素宽度,然后设置fixed宽度。下面是一个实际代码例子:

ts 复制代码
    // Set fixed toolbar width
    const editorOutside = document.querySelector('.tiptap-editor-outside');
    if (editorOutside) {
      const width = editorOutside.clientWidth;
      const toolbars = document.querySelectorAll('.tiptap-editor-outside .fixed-toolbar');
      toolbars.forEach((toolbar) => {
        (toolbar as HTMLElement).style.width = width + 'px';
      });
    }
相关推荐
毕设源码-赖学姐1 天前
【开题答辩全过程】以 基于VUE的环保网站设计为例,包含答辩的问题和答案
前端·javascript·vue.js
ZTrainWilliams1 天前
swagger-mcp-toolkit 让 AI编辑器 更快“读懂并调用”你的接口
前端·后端·mcp
伊步沁心1 天前
深入 useEffect:为什么 cleanup 总比 setup 先跑?顺手手写节流防抖 Hook
前端
小J听不清1 天前
CSS 字体样式全解析:字体类型 / 大小 / 粗细 / 样式
前端·javascript·css·html·css3
500佰1 天前
pencil on claude 让设计师和程序员少吵架的一种可能
前端
Jane-lan1 天前
NVM安装以及可能的坑
前端·node·nvm
幽络源小助理1 天前
Typecho大前端新闻博客主题源码下载:资讯门户风格模板安装教程 | 幽络源
前端
简离1 天前
Git 一次性清理已跟踪但应忽略文件
前端·git
清水寺小和尚1 天前
# 告别魔法:带你彻底搞透 Agent Loop、Skills、Teams 与 MCP 协议
前端
小蜜蜂dry1 天前
nestjs学习 - 管道(pipe)
前端·nestjs