0

I have a div with position absolute and width:100% inside a table cell and the width is calculated to window width not to table cell width. The table cell width is also variable so I need that the width of absolute div to be the same as table cell width. How can I do that?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
MaPa
  • 65
  • 5
  • 8

3 Answers3

1

From w3schools.com

An absolute position element is positioned relative to the first parent element that has a position other than static.

That part often gets overlooked I think.

So, try setting the td to position:relative and see if that gets you what you are after.

Matt
  • 3,778
  • 2
  • 28
  • 32
1

This is the way I got this to work:

<table border="1" class='rel'>
    <tr>
        <td><div class='abs'>row 1, cell 1</div></td>
        <td>row 1, cell 2</td>
    </tr>
    <tr>
        <td>row 2, cell 1</td>
        <td>row 2, cell 2</td>
    </tr>
</table>

* { margin: 0; padding: 0; }

.rel { 
    position: relative; 
}

.abs { 
    position: absolute;
    background-color: red;
    top: 1px;  /* offset because of table border */
    left: 1px;
}

Notice the relative style is applied to the table not the tr or td. When I applied it to the td (what i expected was going to be necessary) it did not work in Chrome. Here is a jsFiddle for you to play with:

http://jsfiddle.net/bNweT/1/

Hope this helps.

Bob

rcravens
  • 8,320
  • 2
  • 33
  • 26
  • This fails on FireFox...still looking a bit. – rcravens Feb 07 '11 at 15:19
  • After playing around a bit, I could not get it to work on FireFox unless I added another div inside the table cell to act as the relative parent container. Here is an updated jsFiddle: http://jsfiddle.net/bNweT/2/ – rcravens Feb 07 '11 at 15:25
0

I believe that this can be done only via JavaScript.

Update

I tried width: auto;, but if it has position absolute it does not take the width of the parent element in DOM.

(I am testing in Chrome and Firefox)

Community
  • 1
  • 1
Lordalcol
  • 990
  • 7
  • 22