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

62,713

Solution 1

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.

Solution 2

Yes. Set outer to position: relative.

http://jsfiddle.net/57673/

.outer
{
  width: 50%;
  height: 200px;
  position: relative;
  border: 1px solid red;
}

.inner
{
  width: 100%;
  position: absolute;
  height: 100%;
  border: 1px solid blue;
}

Solution 3

I had an element that had to be position:absolute in a project and I found that setting width to max-content fixed that for me.
It seems to be well supported across modern browsers. Check this link for more info: Mozilla.org (max-content) .

Share:
62,713
Charles
Author by

Charles

Updated on October 17, 2021

Comments

  • Charles
    Charles over 2 years

    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?

  • Charles
    Charles over 11 years
    Thanks for the help! This was annoying me for about an hour. I'm glad the solution is so simple :)
  • Lebowski156
    Lebowski156 about 11 years
    OHHH AHHH!!! I spent the last 5 hours trying to fix this damn site I've been working on. Thank you so much for this. Can you explain why this works?
  • Rock Lee
    Rock Lee over 5 years
    If your outer div is an <svg> and you want to layer text on top of it, you will need to put another outer <div> like this and use z-indexing instead with both absolute: <div style="{position: relative}"> <svg style="{position: absolute; z-index: 0}" /> <div style="{position: absolute; z-index: 100}">This is my Svg label!</div> </div> I had this problem, and this solution worked for me! Sadly, <svg>'s can't really have children.
  • alex067
    alex067 over 2 years
    You just saved me like 4 hours of debugging, thank you!