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

为何fixed父元素的fixed子元素与absolute父元素的absolute子元素尺寸不同?

为什么fixed子元素和absolute子元素设置相同比例尺寸却大小不同?

核心原因很明确:fixed定位元素的百分比尺寸是相对于视口(浏览器可视区域)计算的,而absolute定位元素的百分比尺寸是相对于最近的非static定位父元素计算的。

结合你的代码具体拆解:

  • 黄色的.fixedchild是fixed定位,它的w-[20%] h-[20%]直接取视口宽度和高度的20%,完全不受父元素.fixexparent的影响——哪怕父元素是fixed定位,fixed子元素依然以视口为基准。
  • 粉色的.anotherchild是absolute定位,它的父元素.child是absolute定位(属于非static定位),所以它的w-[20%] h-[20%]取父元素.child尺寸的20%。而.child本身是视口的50%×50%,所以粉色元素实际是视口的10%×10%,自然比黄色元素小一半。

如果想让两个子元素大小一致,只需要把.fixedchild的定位改成absolute,让它以父元素.fixexparent为基准计算尺寸:

import React from "react";

const App = () => {
  return (
    <div className="maincontainer w-full h-screen">
      <div className="fixexparent fixed w-[50%] h-[50%] bg-emerald-200 right-0 bottom-0">
        {/* 将fixed改为absolute,尺寸变为父元素的20% */}
        <div className="fixedchild absolute w-[20%] h-[20%] bg-yellow-200"></div>
      </div>
      <div className="child absolute bg-blue-200 w-[50%] h-[50%]">
        <div className="anotherchild absolute bg-rose-200 w-[20%] h-[20%] bottom-0 right-0"></div>
      </div>
    </div>
  );
};

export default App

内容的提问来源于stack exchange,提问作者Vaikruta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 10:42:39