merge existing columns using CSS

31.3k views Asked by At

I have a table. The table is generated by some server side code which I can't change but I can add some CSS to style.

<table>
<tbody>
<tr>
 <td>row 1 column 1</td>
 <td>row 1 column 2</td>

</tr>
    </tbody>
</table>

Is there a way of merging the two columns using CSS and not JQuery

  |row1 column1 |row 1 column 2 |
  |             |               |

get an output like

| row 1 column2  |
|                |  
2

There are 2 answers

2
Stewartside On

This isn't possible within CSS, even when you say they're block level elements.

They are still two separate elements and HTML will render them as such.

As shown below:

td {
  border: 1px solid black;
}
.block * {
  display: block;
}
.border-collapse {
  border-collapse: collapse;
  margin: 0;
}
<table>
  <tbody>
    <tr>
      <td>row 1 column 1</td>
      <td>row 1 column 2</td>

    </tr>
  </tbody>
</table>

<table class="block">
  <tbody>
    <tr>
      <td>row 1 column 1</td>
      <td>row 1 column 2</td>

    </tr>
  </tbody>
</table>

<table class="border-collapse">
  <tbody>
    <tr>
      <td>row 1 column 1</td>
      <td>row 1 column 2</td>

    </tr>
  </tbody>
</table>

I believe you are going to have to try and change the html, use the colspan attribute:

<table>
  <tbody>
    <tr>
      <td colspan="3">Here I need a cell by all width</td>
    </tr>
    <tr>
      <td>TD 1</td>
      <td>TD 2</td>
      <td>TD 3</td>
    </tr>
  </tbody>
</table>

The colspan attribute defines the number of columns a cell should span.

There is a related attribute rowspan that achieves the same for rows.

One last dirty option is to always set one of the elements to display: none and the other width: 100%

table {
  width: 400px;
}
table tr td {
  border: 1px solid black;
}

table.td_hide tr td:first-child {
  display: none;
}

table.td_hide tr td:last-child {
  width: 100%;
}
<table>
  <tr>
    <td>Row One</td>
    <td>Row Two</td>
  </tr>
</table>

<table class="td_hide">
  <tr>
    <td>Row One</td>
    <td>Row Two</td>
  </tr>
</table>

0
Jackson On

Try to display the elements as block elements like this:

table, tbody, tr, td {
    display: block;
}