如何使固定定位的 div 继承父元素的宽度?

9

有没有办法使固定定位的div继承父元素的宽度?

我知道固定宽度是相对于窗口的,所以这段代码行不通:

#wrapper{
        position: relative;
        width:500px;
        height: 20px;
        background-color: blue;
}

#header{
        position: fixed;
        width: 100%;
        height: 20px;
        background-color: rgba(255,0,0,0.5);
}
<div id="wrapper">
  #wrapper
        <div id="header">
          #header
        </div>
    </div>

    

2个回答

11
使用inherit值来设置#header选择器上的width属性。 为什么这样做有效 通过将position: fixed指定给#header元素,#header元素的位置是根据CSS2规范中指定的视口计算的。

http://www.w3.org/TR/2011/REC-CSS2-20110607/visuren.html#positioning-scheme

然而,position: fixed 不会改变DOM结构,这意味着#wrapper元素仍然是#header元素的父级。因此,即使其位置是相对于视口确定的,#header仍然可以从其父元素继承属性值。
还要注意,如果为宽度指定百分比值,则固定元素将根据视口计算该值,如规范所述。但是,这不适用于width: inherit,它从父元素而不是视口获取其值。
参见:http://www.w3.org/TR/2011/REC-CSS2-20110607/visudet.html#propdef-width 例如,如果您向#wrapper添加color属性,则#header将继承该属性。
区别在于width的初始/默认值为auto,而color的初始/默认值为inherit。要获取父元素的宽度属性,您需要指定width: inherit,而不是width: 100%注意:父元素和包含块之间有微妙的区别。在大多数情况下,两者是相同的,但对于固定定位的元素,它们是不同的。

#wrapper {
  position: relative;
  width: 500px;
  height: 20px;
  background-color: blue;
  color: white;  /* for demo */
}
#header {
  position: fixed;
  width: inherit;
  height: 20px;
  background-color: rgba(255, 0, 0, 0.5);
}
<div id="wrapper">
  #wrapper
  <div id="header">
    #header
  </div>
</div>


@Morpheus 好问题,我正在查阅CSS规范以弄清楚它为什么有效,这并不明显。 - Marc Audet
谢谢,这真的很有用。 - Alaa Saleh
如果这个答案帮助您解决了问题,请记得点赞。欢迎来到StackOverflow! - Marc Audet
@MarcAudet 有什么发现吗? - Morpheus
这个答案太棒了,谢谢@Marc Audet!如果父元素是一个具有flex-grow: 1属性以填充剩余空间的flex项,如何处理?在https://dev59.com/0ZLea4cB1Zd3GeqPyy_9发布了一个新问题。 - jabram
显示剩余3条评论

0

更改

#wrapper{
    position: relative;
    width:500px;
}

#wrapper{
    position: absolute;
    width:500px;
}

我知道“absolute”会使它相对于父元素定位,但我需要它是固定的,这样当用户向下滚动时它不会消失。 - Alaa Saleh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接