Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way for "position:absolute" div to retain relative width?

Let's say I have two divs, one inside the other, like so:

<html>   <body>     <div id="outer" style="width:50%">       <div id="inner" style="width:100%">       </div>     </div>   </body> </html> 

Right now, the inner div has a width of 100% of 50% of the screen size, or 50% of the screen size. If I were to change the inner div to position absolute, like this:

<html>   <body>     <div id="outer" style="width:50%">       <div id="inner" style="position:absolute;width:100%">       </div>     </div>   </body> </html> 

In this case the inner div takes up 100% of the screen space, because its position is set to absolute.

My question is this: Is there any way to maintain relative width of the inner div while its position is set to absolute?

like image 427
Charles Avatar asked Jan 14 '13 21:01

Charles


People also ask

Can a div be position absolute and relative?

If you position it as absolute , then you're positioning it relative to its closest ancestor which is fixed or relative ... Clearly, nothing can be absolute and relative at the same time. Either you want the element to position itself based on another ancestor's position or based on the page flow.

Why does position absolute change width?

It is because absolutely positioned elements do not behave as block level elements and do not flow after each other like normal <div>does.

Does margin auto work with position absolute?

If the element is position absolutely, then it isn't relative, or in reference to any object - including the page itself. So margin: auto; can't decide where the middle is.


1 Answers

Add position:relative to your outer div.

update: It works because positions in position: absolute are relative to the first parent that has some positioning (other than static). In this case there was no such container, so it uses the page.

like image 151
Bror Avatar answered Sep 29 '22 21:09

Bror