Derek 朕會功夫
Derek 朕會功夫

Reputation: 94409

100% width on position absolute element

I'm trying to make a div to have 100% width of its parent element (body). body has a horizontal scrollbar and the div only takes up the viewport width. To fix this I added

width: inherit;

to it. I expected it to work since inherit, according to the definition, means "taking the computed value of the property from its parent element". I tested it in a simpler model and it works: http://jsfiddle.net/DerekL/EYgT9/.

However, when I apply the code to my actual project it doesn't work as expect. It doesn't even seem to follow the definition.

enter image description here
As you can see, the div has inherit as its width. But it's computed width is not the width of its parent body, instead it's some other value 302px.

Now let's take a look body:
enter image description here
body clearly has a width of 470px.

I couldn't figure out what's the reason behind this, making it not working as expected. The overall structure is the same as the fiddle, but result aren't the same.

What are the possible reason of this happening? Sorry that I couldn't post the relevant part of the code since I don't even where it's causing this issue.

Upvotes: 2

Views: 1970

Answers (2)

Gruja
Gruja

Reputation: 31

Your body tag has position static and for the position absolute to work properly the parent element must have position set on either relative or absolute. Just add position: relative or absolute; to the body tag.

Upvotes: 0

Zach Saucier
Zach Saucier

Reputation: 26034

This is because the element with position:absolute is positioned in reference to <html> since <body> doesn't have a position to put it in reference to. Thus, it's inheriting its width from html as well.

To fix it, add position:relative to body

Demo

Upvotes: 3

Related Questions