Georgi Georgiev
Georgi Georgiev

Reputation: 1623

Table doesn't fit in parent div

Here is an example of what I am trying to do(put a table in a div and make it fill the div): ex1_jsfiddle

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
  height: 100%;
  table-layout: fixed;
}
td,
th {
  border: 1px solid;
  text-align: left;
  padding: 0px 55px 0px 55px;
}
tr:nth-child(even) {
  background-color: lightgreen;
}
tr {
  margin-top: 0;
}
aside {
  background-color: lightblue;
  border: solid 2px;
  position: absolute;
  float: left;
  height: 100%;
  width: 15%;
}
#table_div {
  float: left;
  border: solid 2px;
  margin-left: 25%;
  height: 300px;
  width: 700px;
  border-color: red;
}
<aside>sidebar</aside>
<div id="table_div">
  <table>
    
    <tr>
      
      <th>Firstname</th>
      
      <th>Lastname</th>
      
      <th>Age</th>
      </tr>
    <tr>
      <td>Jill</td>
      <td>Smith</td>
      <td>50</td>
    </tr>
    <tr>
      <td>Eve</td>
      <td>Jackson</td>
      <td>94</td>
    </tr>
    <tr>
      <td>John</td>
      <td>Doe</td>
      <td>80</td>
    </tr>
  </table>
</div>

The problem is that as you see in ex1 the table is getting out of the parent div. And the most strange thing is that if I indent the elements between <div_id="table_div> and </div> with 1 tab, it works BUT ONLY in jsfiddle: ex2_jsfiddle

When I try it in my browser(Chrome) it doesn't work.

So, can someone explain to me what is going on?

Upvotes: 3

Views: 1300

Answers (3)

Srikanth Reddy
Srikanth Reddy

Reputation: 345

Here the solution! please change '#talbd_div' width to %

#table_div {
  float: left;
  border: solid 2px;
  padding-left: 15%;
  height: 300px;
  width: 80%;
  border-color: red;
}

Upvotes: 0

Oriol
Oriol

Reputation: 288520

The problem is that you have some   characters there. They seem harmeless spaces, but in fact they are non-breaking spaces (&nbsp;), which HTML does not consider space characters.

<div>IT WORKS!</div>

<aside>sidebar</aside>
<div id="table_div">
<table >
&nbsp; <tr>
&nbsp;&nbsp;&nbsp; <th>Firstname</th>
&nbsp;&nbsp;&nbsp; <th>Lastname</th>
&nbsp;&nbsp;&nbsp; <th>Age</th>
&nbsp; </tr>
  <tr>
    <td >Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
  <tr>
    <td>John</td>
    <td>Doe</td>
    <td>80</td>
  </tr>
</table>
</div>

These &nbsp; are not allowed there, so the parser moves them before the table. This produces that empty line.

Upvotes: 4

Joshua H
Joshua H

Reputation: 774

It looks like in JSfiddle, the "tab-less" version (ex1_jsfiddle) register a character in between <div> and <table> and hence, pushing the table down.

I try it in chrome and it exactly looks like what @zer00ne comment. But when I put an empty character e.g. &nbsp, it looks like your ex1_jsfiddle

Upvotes: 1

Related Questions