Search code examples
htmlcsswidthfixed

How can I make a fixed positioned div inherit width of parent?


Is there a way a fixed positioned div can inherit the width of a parent?

I know fixed width is relative to the window's so this code doesn't work:

#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>

    


Solution

  • Use the inherit value for the width property on the #header selector.

    Why This Works

    By specifying position: fixed to the #header element, the #header element's position is calculated with respect to the viewport as specified in the CSS2 specification:

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

    However, position: fixed does not change the DOM structure, which means that the #wrapper element is still the parent of the #header element. As a consequence, the #header can still inherit property values from its parent element, even though its position is determined with respect to the viewport.

    Note also that if you specify a percentage value for the width, the fixed element will calculate the value based on the viewport, as stated in the specification. However, this does not pertain to width: inherit, which takes its value from the parent element, not the viewport.

    See: http://www.w3.org/TR/2011/REC-CSS2-20110607/visudet.html#propdef-width

    For example, if you added the color property to #wrapper, it would be inherited by #header.

    The distinction is that the initial/default value for width is auto whereas for color it is inherit. To get the parent's with property, you need to specify width: inherit, not width: 100%;

    Note: There is a subtle distinction between the parent element and the containing block. In most cases, the two are the same, but for fixed positioned elements, they are different.

    #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>