Otaku Kyon Otaku Kyon - 6 months ago 16
CSS Question

CSS: Aligned tables overlapping DIV container

I created two tables, which are displayed side by side using the attribute

align="left"
&
align="right"
in the html source code. I packed these tables into a div container with the assigned class
outerdiv
, so that I can add a linear-gradient background behind them. Unfortunately, the tables do not get displayed inside of the div.

I tried adding
table-layout:fixed;
to
.table
, as some sites recommended me. I also set
border-collapse:separate;
to the table cell.

How can I place the background correctly behind the tables?



.table {
width: 48%;
margin: 1% !important;
background: red;
border-spacing: 20px;
table-layout: fixed;
}
.outerdiv {
border: 1px solid rgb(164, 164, 164);
border-radius: 8px;
background: transparent linear-gradient(rgb(255, 255, 255), rgb(222, 222, 222)) repeat scroll 0% 0%;
clear: both;
}

<div class="outerdiv">
<table class="table" align="left">
<tbody>
<tr>
<td>4
</td>
</tr>
<tr>
<td>Apples
</td>
</tr>
</tbody>
</table>
<table class="table" align="right">
<tbody>
<tr>
<td>2
</td>
</tr>
<tr>
<td>Bananas
</td>
</tr>
</tbody>
</table>
<p></p>
</div>




Answer

Just add display: inline-block to your outerdiv class. This will correctly wrap the tables inside of the parent div. Like so:

.table {
  width: 48%;
  margin: 1% !important;
  background: red;
  border-spacing: 20px;
  table-layout: fixed;
}
.outerdiv {
  border: 1px solid rgb(164, 164, 164);
  border-radius: 8px;
  background: transparent linear-gradient(rgb(255, 255, 255), rgb(222, 222, 222)) repeat scroll 0% 0%;
  clear: both;
  display: inline-block;
}
<div class="outerdiv">
  <table class="table" align="left">
    <tbody>
      <tr>
        <td>4
        </td>
      </tr>
      <tr>
        <td>Apples
        </td>
      </tr>
    </tbody>
  </table>
  <table class="table" align="right">
    <tbody>
      <tr>
        <td>2
        </td>
      </tr>
      <tr>
        <td>Bananas
        </td>
      </tr>
    </tbody>
  </table>
  <p></p>
</div>

Also, Maximillian makes a good point in his post about the align attribute you seem to be using. It is no longer used in HTML5. Instead, either give your tables float: left. Like this:

.table {
  width: 48%;
  margin: 1% !important;
  background: red;
  border-spacing: 20px;
  table-layout: fixed;
  float: left;
}
.outerdiv {
  border: 1px solid rgb(164, 164, 164);
  border-radius: 8px;
  background: transparent linear-gradient(rgb(255, 255, 255), rgb(222, 222, 222)) repeat scroll 0% 0%;
  clear: both;
  display: inline-block;
}
<div class="outerdiv">
  <table class="table">
    <tbody>
      <tr>
        <td>4
        </td>
      </tr>
      <tr>
        <td>Apples
        </td>
      </tr>
    </tbody>
  </table>
  <table class="table">
    <tbody>
      <tr>
        <td>2
        </td>
      </tr>
      <tr>
        <td>Bananas
        </td>
      </tr>
    </tbody>
  </table>
  <p></p>
</div>