Make a DIV fill an entire table cell

I've seen this question and googled a bit, but nothing so far has worked. I figure it's 2010 now (those questions/answers are old and, well, unanswered) and we have CSS3! Is there any way to get a div to fill an entire table cell's width and height using CSS?

I don't know what the width and/or height of the cell will be ahead of time, and setting the div's width and height to 100% does not work.

Also, the reason I need the div is because I need to absolutely position some elements outside of the cell, and position: relative does not apply to td s, so I need a wrapper div.


The following code works on IE 8, IE 8's IE 7 compatibility mode, and Chrome (not tested elsewhere):

<table style="width:100px"> <!-- Not actually necessary; just makes the example text shorter -->
   <tr><td>test</td><td>test</td></tr>
   <tr>
      <td style="padding:0;">
         <div style="height:100%; width:100%; background-color:#abc; position:relative;">
            <img style="left:90px; position:absolute;" src="../Content/Images/attachment.png"/>
            test of really long content that causes the height of the cell to increase dynamically
         </div>
      </td>
      <td>test</td>
   </tr>
</table>

You said in your original question that setting width and height to 100% didn't work, though, which makes me suspect that there is some other rule overriding it. Did you check the computed style in Chrome or Firebug to see if the width/height rules were really being applied?

Edit

How foolish I am! The div was sizing to the text, not to the td . You can fix this on Chrome by making the div display:inline-block , but it doesn't work on IE. That's proving trickier...


div height=100% in table cell will work only when table has height attribute itself.

<table border="1" style="height:300px; width: 100px;">
 <tr><td>cell1</td><td>cell2</td></tr>
 <tr>
   <td>
     <div style="height: 100%; width: 100%; background-color:pink;"></div>
   </td>
   <td>long text long text long text long text long text long text</td>
 </tr>
</table>

UPD in FireFox you should also set height=100% value to the parent TD element


If your reason for wanting a 100% div inside a table cell was to be able to have a background color extend to the full height but still be able to have spacing between the cells, you could give the <td> itself the background color and use the CSS border-spacing property to create the margin between the cells.

If you truly need a 100% height div, however, then as others here have mentioned you need to either assign a fixed height to the <table> or use Javascript.

链接地址: http://www.djcxy.com/p/88182.html

上一篇: 基于网页的布局

下一篇: 使DIV填满整个表格单元格