bɪˈɡɪnə
bɪˈɡɪnə

Reputation: 1085

How to remove empty space in a table cell ?

In the code below I have set max-width for table cells, so all of them have equal width irrespective of content they carry and vertical-align is set to top. But as you see first cell is quite lengthy as compared to second and third so there is huge space left between 2nd-5th and 3rd-6th table cells. Is there any way to remove that space ? I mean I want 5th and 6th cells to follow the above cells immediately and not to wait for 1st cell to end.

table tr td {
  vertical-align:top;
  max-width:90px;
  background-color: #dedede;
  color: black
}
<table>
  <tr>
    <td>this is first cell. this will be quite lengthy</td>
    <td>this is second cell</td>
    <td>this is third cell</td>
  </tr>

  <tr>
    <td>this is fouth cell</td>
    <td>this is fifth cell</td>
    <td>this is sixth cell</td>
  </tr>
</table>

Upvotes: 0

Views: 2292

Answers (2)

Austin Brown
Austin Brown

Reputation: 1

If I understand correctly, you don't care if cells 5 and 6 align with cell 4, as long as they align with each other and get rid of that empty space. In many cases it's better to use divs than tables for this sort of thing, but here's a solution that retains tables.

You'll have to create a second table if you want to break row alignment, so the first table will have cells 1 and 4 and the second will have cells 2, 3, 5, and 6. For your style, use display:inline-block to get the tables to sit next to each other, and enclose them in <div>s (never use nested tables) with display:inline; vertical align:top; if you want the two tables to align at the top. The end result is something like this:

<head>

<style>
table tr td {
  vertical-align:top;
  max-width:90px;
  background-color: #dedede;
  color: black;
}
.talign{
display:inline-block;
}
.dalign{
display:inline;
vertical-align:top;
}
</style>
</head>
<body>
<div class='dalign'>
<table class='talign'>
  <tr>
    <td>this is first cell. this will be quite lengthy</td>
  </tr>
  <tr>
    <td>this is fouth cell</td>
  </tr>
</table>
</div>
<div class='dalign'>
<table class='talign'>
  <tr>
    <td>this is second cell</td>
    <td>this is third cell</td>
  </tr>
  <tr>
    <td>this is fifth cell</td>
    <td>this is sixth cell</td>
  </tr>
</table>
</div>
</body>

Upvotes: 0

Optiq
Optiq

Reputation: 3262

The problem with what you want is tables are set up to function like that so it keeps everything aligned and organized. As mentioned you might want to look more into the masonry layout if you want separate squares to stack together like different sized bricks, a table won't work in that instance because it's not built to work that way.

Upvotes: 2

Related Questions