位置为固定且宽度为 100% 的 CSS 元素大于其父元素

问题描述 投票:0回答:1

抱歉我之前的问题措辞不好。

我有一个具有

position:fixed
width:100%
的元素。问题是父元素都没有固定宽度。所以我的元素实际上比它的任何父元素都大。

我的代码的实现非常复杂,但我认为我能够简化事情。在下面的代码中,您会注意到绿色框比其父元素大。

export default function App() {
  return (
    <div
      style={{
        width: "100%",
        padding: "0px 15px",
        boxSizing: "border-box",
        height: "80px",
      }}
    >
      <div
        style={{
          width: "100%",
          border: "1px solid blue",
          height: "80px",
        }}
      >
        <div
          style={{
            width: "100%",
            border: "1px solid transparent",
            height: "80px",
          }}
        >
          <div style={{ width: "inherit", height: "25px" }}>
            <div style={{ width: "inherit", height: "25px" }}>
              <div
                style={{
                  width: "inherit",
                  position: "fixed",
                  height: "25px",
                  border: "1px solid green",
                }}
              ></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
javascript html css
1个回答
1
投票

https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block

如果position属性固定,则建立包含块 通过视口(在连续媒体的情况下)或页面区域(在 分页媒体的情况)。

即使父级有宽度,它也会使用视口作为参考。也许你可以尝试

position: sticky
来达到相同的效果,但使用父级作为参考点

© www.soinside.com 2019 - 2024. All rights reserved.