Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In CSS, how can I make a table expand to fill a container div?

I want to "carve out" spaces on the screen by creating several container DIVs, then fill in the content in each of the DIVs. in one case, I need to fill up with a table.

the innermost part of the table are jpeg <img>. I do not want to use fixed pixel sizes anywhere, so that the content will shrink nicely in different size browsers.

After repeated trial and errors, and some reading on the internet, I figured out that to let the whole chain container-div--->table-->tbody-->tr-->td-->img fit nicely in size, I must make sure that each of these elements have the following attributes "height:100%; width:100; position:relative" (the img position itself can be absolute ).

This works fine with a table of 1 row only. but if I have multiple rows, it looks that the row height is calculated naiively from its parent, which is tbody, because if I have 2 rows, each row is still as high as the tbody. but even after I manually divide the height of TR by 2, it does not exactly fit into the container.

So how can I make the table shrink automatically to the surrounding container?

    <style type="text/css">

div {
border : 2px solid red;
}

#bottom-banner {
height:40%;
}

#bottom-banner tbody {
position:relative;
height:100%;
width:100%;
}

#bottom-banner tr {
max-height:100%;
width:100%;
position:relative;
height:100%;
}


<style type="text/css">

div {
border : 2px solid red;
}

#bottom-banner {
height:40%;
}

#bottom-banner tbody {
position:relative;
height:100%;
width:100%;
}

#bottom-banner tr {
max-height:100%;
width:100%;
position:relative;
height:100%;
}
#bottom-banner table {
position:relative;
height:100%;
width:100%;
}

#bottom-banner div {
position:relative;
height:100%;
width:100%;
}

#bottom-banner img {
height:100%;
position:absolute;
right:0;
left:0;
margin:auto;
top:0;
bottom:0;
width:auto;
}
</style>

<div id="bottom-banner">

<table><tbody>
<tr>
<td >
<div><img src="11a2.jpg"/></div>
</td>
</tr>

<tr>
<td >
<div><img src="11a2.jpg"/></div>
</td>
</tr>

</tbody></table>
</div>
like image 841
teddy teddy Avatar asked Apr 28 '14 14:04

teddy teddy


Video Answer


1 Answers

Just set the width and height of your table to 100%. But the parent div of the table must have an assigned height if the cells are empty they will not take up any vertical space without a height specified.

div { width: 100%;height: 500px;border: 5px yellow solid; }
table { width: 100%;height: 100%;border: 3px red double; }
<div>
  <table>
    <tr>
      <td bgcolor="#2062AF"></td>
      <td bgcolor="#05BDB0"></td>
      <td bgcolor="#FEFCC2"></td>
      <td bgcolor="#FAA72A"></td>
      <td bgcolor="#CD3450"></td>
    </tr>
  </table>
</div>
like image 188
davidcondrey Avatar answered Sep 20 '22 13:09

davidcondrey