Skip to content Skip to sidebar Skip to footer

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:

Solution 1:

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);
}
<divid="wrapper">
  #wrapper
  <divid="header">
    #header
  </div></div>

Solution 2:

Change

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

to

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

Post a Comment for "How Can I Make A Fixed Positioned Div Inherit Width Of Parent?"