div style absolute in a table cell

戏子无情 提交于 2019-12-12 01:37:54

问题


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?


回答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.




回答2:


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




回答3:


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)



来源:https://stackoverflow.com/questions/4922707/div-style-absolute-in-a-table-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!