Rama Rao M
Rama Rao M

Reputation: 3051

Table colspan looks different

I have a table of 2 rows and 3 columns and I want to set colspan=2 to 1x2 cell and 2x1 cell. But output seems something different than I expected.

Expected one: enter image description here

But the output that's shown: enter image description here

Here is the html:

<!DOCTYPE HTML PUBLIC>
<html>
 <body>
    <table border=1 cellpadding=0 cellspacing=0 width=100%>
    <tr>
        <td >1x1</td>
        <td COLSPAN=2>1x2</td>
    </tr>
    <tr>
        <td COLSPAN=2>2X1</td>
        <td>2x2</td>
    </tr>
    </table>
 </body>
</html>

Can somebody help me to achieve the expected output using table and colspan?

Upvotes: 2

Views: 131

Answers (2)

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201568

There is nothing in the table that requires any nonzero width for the second column, since the slots in it are shared with other slots. There are various ways to deal with this.

Setting table-layout: fixed as in @Danield’s answer addresses the issue by forcing fixed table layout. The algorithm for it divides the available space evenly to the columns, when there is no width requirement expressed in CSS or HTML. If even division is what you want (even though your “Expected one” is somewhat different), this is the simplest way.

Another way is to set widths explicitly, e.g. in this case (see jsfiddle)

td {
  width: 33.33%;
}
td[colspan=2] {
  width: 66.67%;
}

This is unnecessarily clumsy if you just want even division. But if you want e.g. the column widths to be 25%, 50%, 25%, you can use the following (see other jsfiddle):

<style>
col {
  width: 25%;
}
col:nth-of-type(2) {
  width: 50%;
}
</style>

... ...

In cases like this, it is easier to set widths for columns directly (by styling col elements) rather than indirectly by setting widths for cells (which may occupy several columns).

Upvotes: 2

Danield
Danield

Reputation: 125443

Add the following CSS class:

table {
    table-layout: fixed;
}

FIDDLE

Upvotes: 5

Related Questions