如何使固定的div继承父级的宽度?

Ala*_*leh 7 html css fixed width

有没有办法固定定位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);
}
Run Code Online (Sandbox Code Playgroud)
<div id="wrapper">
  #wrapper
        <div id="header">
          #header
        </div>
    </div>

    
Run Code Online (Sandbox Code Playgroud)

Mar*_*det 10

在选择器上使用属性的inherit值.width#header

为何如此有效

通过指定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

例如,如果您将color属性添加到#wrapper,则将继承该属性#header.

区别在于它的初始/默认值width是,autocolor它是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);
}
Run Code Online (Sandbox Code Playgroud)
<div id="wrapper">
  #wrapper
  <div id="header">
    #header
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)