[html] Colspan all columns

How can I specify a td tag should span all columns (when the exact amount of columns in the table will be variable/difficult to determine when the HTML is being rendered)? w3schools mentions you can use colspan="0", but it doesn't say exactly what browsers support that value (IE 6 is in our list to support).

It appears that setting colspan to a value greater than the theoretical amount of columns you may have will work, but it will not work if you have table-layout set to fixed. Are there any disadvantages to using an automatic layout with a large number for colspan? Is there a more correct way of doing this?

This question is related to html html-table tablelayout

The answer is


For IE 6, you'll want to equal colspan to the number of columns in your table. If you have 5 columns, then you'll want: colspan="5".

The reason is that IE handles colspans differently, it uses the HTML 3.2 specification:

IE implements the HTML 3.2 definition, it sets colspan=0 as colspan=1.

The bug is well documented.


If you want to make a 'title' cell that spans all columns, as header for your table, you may want to use the caption tag (http://www.w3schools.com/tags/tag_caption.asp / https://developer.mozilla.org/en-US/docs/Web/HTML/Element/caption) This element is meant for this purpose. It behaves like a div, but doesn't span the entire width of the parent of the table (like a div would do in the same position (don't try this at home!)), instead, it spans the width of the table. There are some cross-browser issues with borders and such (was acceptable for me). Anyways, you can make it look as a cell that spans all columns. Within, you can make rows by adding div-elements. I'm not sure if you can insert it in between tr-elements, but that would be a hack I guess (so not recommended). Another option would be messing around with floating divs, but that is yuck!

Do

<table>
    <caption style="gimme some style!"><!-- Title of table --></caption>
    <thead><!-- ... --></thead>
    <tbody><!-- ... --></tbody>
</table>

Don't

<div>
    <div style="float: left;/* extra styling /*"><!-- Title of table --></div>
    <table>
        <thead><!-- ... --></thead>
        <tbody><!-- ... --></tbody>
    </table>
    <div style="clear: both"></div>
</div>

Another working but ugly solution : colspan="100", where 100 is a value larger than total columns you need to colspan.

According to the W3C, the colspan="0" option is valid only with COLGROUP tag.


If you're using jQuery (or don't mind adding it), this will get the job done better than any of these hacks.

function getMaxColCount($table) {
    var maxCol = 0;

    $table.find('tr').each(function(i,o) {
        var colCount = 0;
        $(o).find('td:not(.maxcols),th:not(.maxcols)').each(function(i,oo) {
            var cc = Number($(oo).attr('colspan'));
            if (cc) {
                colCount += cc;
            } else {
                colCount += 1;
            }
        });
        if(colCount > maxCol) { maxCol = colCount };
    });

    return maxCol;

}

To ease the implementation, I decorate any td/th I need adjusted with a class such as "maxCol" then I can do the following:

$('td.maxcols, th.maxcols').each(function(i,o) {
    $t = $($(o).parents('table')[0]); $(o).attr('colspan',  getMaxColCount($t));
});

If you find an implementation this won't work for, don't slam the answer, explain in comments and I'll update if it can be covered.


For IE 6, you'll want to equal colspan to the number of columns in your table. If you have 5 columns, then you'll want: colspan="5".

The reason is that IE handles colspans differently, it uses the HTML 3.2 specification:

IE implements the HTML 3.2 definition, it sets colspan=0 as colspan=1.

The bug is well documented.


Maybe I'm a straight thinker but I'm a bit puzzled, don't you know the column number of your table?

By the way IE6 doesn't honor the colspan="0", with or without a colgroup defined. I tried also to use thead and th to generate the groups of columns but the browser doesn't recognlise the form colspan="0".

I've tried with Firefox 3.0 on windows and linux and it works only with a strict doctype.

You can check a test on several bowser at

http://browsershots.org/http://hsivonen.iki.fi/test/wa10/tables/colspan-0.html

I found the test page here http://hsivonen.iki.fi/test/wa10/tables/colspan-0.html

Edit: Please copy and paste the link, the formatting won't accept the double protocol parts in the link (or I am not so smart to correctly format it).


As a partial answer, here's a few points about colspan="0", which was mentioned in the question.

tl;dr version:

colspan="0" doesn't work in any browser whatsoever. W3Schools is wrong (as usual). HTML 4 said that colspan="0" should cause a column to span the whole table, but nobody implemented this and it was removed from the spec after HTML 4.

Some more detail and evidence:

  • All major browsers treat it as equivalent to colspan="1".

    Here's a demo showing this; try it on any browser you like.

    _x000D_
    _x000D_
    td {_x000D_
      border: 1px solid black;_x000D_
    }
    _x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>ay</td>_x000D_
        <td>bee</td>_x000D_
        <td>see</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td colspan="0">colspan="0"</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td colspan="1">colspan="1"</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td colspan="3">colspan="3"</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td colspan="1000">colspan="1000"</td>_x000D_
      </tr>_x000D_
    </table>
    _x000D_
    _x000D_
    _x000D_

  • The HTML 4 spec (now old and outdated, but current back when this question was asked) did indeed say that colspan="0" should be treated as spanning all columns:

    The value zero ("0") means that the cell spans all columns from the current column to the last column of the column group (COLGROUP) in which the cell is defined.

    However, most browsers never implemented this.

  • HTML 5.0 (made a candidate recommendation back in 2012), the WhatWG HTML living standard (the dominant standard today), and the latest W3 HTML 5 spec all do not contain the wording quoted from HTML 4 above, and unanimously agree that a colspan of 0 is not allowed, with this wording which appears in all three specs:

    The td and th elements may have a colspan content attribute specified, whose value must be a valid non-negative integer greater than zero ...

    Sources:

  • The following claims from the W3Schools page linked to in the question are - at least nowadays - completely false:

    Only Firefox supports colspan="0", which has a special meaning ... [It] tells the browser to span the cell to the last column of the column group (colgroup)

    and

    Differences Between HTML 4.01 and HTML5

    NONE.

    If you're not already aware that W3Schools is generally held in contempt by web developers for its frequent inaccuracies, consider this a lesson in why.


Maybe I'm a straight thinker but I'm a bit puzzled, don't you know the column number of your table?

By the way IE6 doesn't honor the colspan="0", with or without a colgroup defined. I tried also to use thead and th to generate the groups of columns but the browser doesn't recognlise the form colspan="0".

I've tried with Firefox 3.0 on windows and linux and it works only with a strict doctype.

You can check a test on several bowser at

http://browsershots.org/http://hsivonen.iki.fi/test/wa10/tables/colspan-0.html

I found the test page here http://hsivonen.iki.fi/test/wa10/tables/colspan-0.html

Edit: Please copy and paste the link, the formatting won't accept the double protocol parts in the link (or I am not so smart to correctly format it).


A CSS solution would be ideal, but I was unable to find one, so here is a JavaScript solution: for a tr element with a given class, maximize it by selecting a full row, counting its td elements and their colSpan attributes, and just setting the widened row with el.colSpan = newcolspan;. Like so...

_x000D_
_x000D_
var headertablerows = document.getElementsByClassName('max-col-span');

[].forEach.call(headertablerows, function (headertablerow) {
    var colspan = 0;
    [].forEach.call(headertablerow.nextElementSibling.children, function (child) {
        colspan += child.colSpan ? parseInt(child.colSpan, 10) : 1;
    });
    
    headertablerow.children[0].colSpan = colspan;
});
_x000D_
html {
  font-family: Verdana;
}
tr > * {
  padding: 1rem;
  box-shadow: 0 0 8px gray inset;
}
_x000D_
  <table>
    <tr class="max-col-span">
      <td>1 - max width
      </td>
    </tr>
    <tr>
      <td>2 - no colspan
      </td>
      <td colspan="2">3 - colspan is 2
      </td>
    </tr>
  </table>
_x000D_
_x000D_
_x000D_

You may need to adjust this if you're using table headers, but this should give a proof-of-concept approach that uses 100% pure JavaScript.


Below is a concise es6 solution (similar to Rainbabba's answer but without the jQuery).

_x000D_
_x000D_
Array.from(document.querySelectorAll('[data-colspan-max]')).forEach(td => {_x000D_
    let table = td;_x000D_
    while (table && table.nodeName !== 'TABLE') table = table.parentNode;_x000D_
    td.colSpan = Array.from(table.querySelector('tr').children).reduce((acc, child) => acc + child.colSpan, 0);_x000D_
});
_x000D_
html {_x000D_
  font-family: Verdana;_x000D_
}_x000D_
tr > * {_x000D_
  padding: 1rem;_x000D_
  box-shadow: 0 0 8px gray inset;_x000D_
}
_x000D_
<table>_x000D_
<thead>_x000D_
  <tr>_x000D_
    <th>Header 1</th>_x000D_
    <th>Header 2</th>_x000D_
    <th>Header 3</th>_x000D_
    <th>Header 4</th>_x000D_
    <th>Header 5</th>_x000D_
    <th>Header 6</th>_x000D_
  </tr>_x000D_
</thead>_x000D_
<tbod><tr>_x000D_
  <td data-colspan-max>td will be set to full width</td>_x000D_
</tr></tbod>_x000D_
</table>
_x000D_
_x000D_
_x000D_


If you're using jQuery (or don't mind adding it), this will get the job done better than any of these hacks.

function getMaxColCount($table) {
    var maxCol = 0;

    $table.find('tr').each(function(i,o) {
        var colCount = 0;
        $(o).find('td:not(.maxcols),th:not(.maxcols)').each(function(i,oo) {
            var cc = Number($(oo).attr('colspan'));
            if (cc) {
                colCount += cc;
            } else {
                colCount += 1;
            }
        });
        if(colCount > maxCol) { maxCol = colCount };
    });

    return maxCol;

}

To ease the implementation, I decorate any td/th I need adjusted with a class such as "maxCol" then I can do the following:

$('td.maxcols, th.maxcols').each(function(i,o) {
    $t = $($(o).parents('table')[0]); $(o).attr('colspan',  getMaxColCount($t));
});

If you find an implementation this won't work for, don't slam the answer, explain in comments and I'll update if it can be covered.


For IE 6, you'll want to equal colspan to the number of columns in your table. If you have 5 columns, then you'll want: colspan="5".

The reason is that IE handles colspans differently, it uses the HTML 3.2 specification:

IE implements the HTML 3.2 definition, it sets colspan=0 as colspan=1.

The bug is well documented.


Maybe I'm a straight thinker but I'm a bit puzzled, don't you know the column number of your table?

By the way IE6 doesn't honor the colspan="0", with or without a colgroup defined. I tried also to use thead and th to generate the groups of columns but the browser doesn't recognlise the form colspan="0".

I've tried with Firefox 3.0 on windows and linux and it works only with a strict doctype.

You can check a test on several bowser at

http://browsershots.org/http://hsivonen.iki.fi/test/wa10/tables/colspan-0.html

I found the test page here http://hsivonen.iki.fi/test/wa10/tables/colspan-0.html

Edit: Please copy and paste the link, the formatting won't accept the double protocol parts in the link (or I am not so smart to correctly format it).


Below is a concise es6 solution (similar to Rainbabba's answer but without the jQuery).

_x000D_
_x000D_
Array.from(document.querySelectorAll('[data-colspan-max]')).forEach(td => {_x000D_
    let table = td;_x000D_
    while (table && table.nodeName !== 'TABLE') table = table.parentNode;_x000D_
    td.colSpan = Array.from(table.querySelector('tr').children).reduce((acc, child) => acc + child.colSpan, 0);_x000D_
});
_x000D_
html {_x000D_
  font-family: Verdana;_x000D_
}_x000D_
tr > * {_x000D_
  padding: 1rem;_x000D_
  box-shadow: 0 0 8px gray inset;_x000D_
}
_x000D_
<table>_x000D_
<thead>_x000D_
  <tr>_x000D_
    <th>Header 1</th>_x000D_
    <th>Header 2</th>_x000D_
    <th>Header 3</th>_x000D_
    <th>Header 4</th>_x000D_
    <th>Header 5</th>_x000D_
    <th>Header 6</th>_x000D_
  </tr>_x000D_
</thead>_x000D_
<tbod><tr>_x000D_
  <td data-colspan-max>td will be set to full width</td>_x000D_
</tr></tbod>_x000D_
</table>
_x000D_
_x000D_
_x000D_


Just use this:

colspan="100%"

It works on Firefox 3.6, IE 7 and Opera 11! (and I guess on others, I couldn't try)


Warning: as mentioned in the comments below this is actually the same as colspan="100". Hence, this solution will break for tables with css table-layout: fixed, or more than 100 columns.


Just want to add my experience and answer to this.
Note: It only works when you have a pre-defined table and a tr with ths, but are loading in your rows (for example via AJAX) dynamically.

In this case you can count the number of th's there are in your first header row, and use that to span the whole column.

This can be needed when you want to relay a message when no results have been found.

Something like this in jQuery, where table is your input table:

var trs = $(table).find("tr");
var numberColumns = 999;
if (trs.length === 1) {
    //Assume having one row means that there is a header
    var headerColumns = $(trs).find("th").length;
    if (headerColumns > 0) {
        numberColumns = headerColumns;
    }
}

use colspan="100%" in table cell and it's working fine.

_x000D_
_x000D_
colspan="100%"
_x000D_
_x000D_
_x000D_


Just use this:

colspan="100%"

It works on Firefox 3.6, IE 7 and Opera 11! (and I guess on others, I couldn't try)


Warning: as mentioned in the comments below this is actually the same as colspan="100". Hence, this solution will break for tables with css table-layout: fixed, or more than 100 columns.


A CSS solution would be ideal, but I was unable to find one, so here is a JavaScript solution: for a tr element with a given class, maximize it by selecting a full row, counting its td elements and their colSpan attributes, and just setting the widened row with el.colSpan = newcolspan;. Like so...

_x000D_
_x000D_
var headertablerows = document.getElementsByClassName('max-col-span');

[].forEach.call(headertablerows, function (headertablerow) {
    var colspan = 0;
    [].forEach.call(headertablerow.nextElementSibling.children, function (child) {
        colspan += child.colSpan ? parseInt(child.colSpan, 10) : 1;
    });
    
    headertablerow.children[0].colSpan = colspan;
});
_x000D_
html {
  font-family: Verdana;
}
tr > * {
  padding: 1rem;
  box-shadow: 0 0 8px gray inset;
}
_x000D_
  <table>
    <tr class="max-col-span">
      <td>1 - max width
      </td>
    </tr>
    <tr>
      <td>2 - no colspan
      </td>
      <td colspan="2">3 - colspan is 2
      </td>
    </tr>
  </table>
_x000D_
_x000D_
_x000D_

You may need to adjust this if you're using table headers, but this should give a proof-of-concept approach that uses 100% pure JavaScript.


try using "colSpan" instead of "colspan". IE likes the camelBack version...


use colspan="100%" in table cell and it's working fine.

_x000D_
_x000D_
colspan="100%"
_x000D_
_x000D_
_x000D_


Just want to add my experience and answer to this.
Note: It only works when you have a pre-defined table and a tr with ths, but are loading in your rows (for example via AJAX) dynamically.

In this case you can count the number of th's there are in your first header row, and use that to span the whole column.

This can be needed when you want to relay a message when no results have been found.

Something like this in jQuery, where table is your input table:

var trs = $(table).find("tr");
var numberColumns = 999;
if (trs.length === 1) {
    //Assume having one row means that there is a header
    var headerColumns = $(trs).find("th").length;
    if (headerColumns > 0) {
        numberColumns = headerColumns;
    }
}

According to the specification colspan="0" should result in a table width td.

However, this is only true if your table has a width! A table may contain rows of different widths. So, the only case that the renderer knows the width of the table if you define a colgroup! Otherwise, result of colspan="0" is indeterminable...

http://www.w3.org/TR/REC-html40/struct/tables.html#adef-colspan

I cannot test it on older browsers, but this is part of specification since 4.0...


For IE 6, you'll want to equal colspan to the number of columns in your table. If you have 5 columns, then you'll want: colspan="5".

The reason is that IE handles colspans differently, it uses the HTML 3.2 specification:

IE implements the HTML 3.2 definition, it sets colspan=0 as colspan=1.

The bug is well documented.


If you want to make a 'title' cell that spans all columns, as header for your table, you may want to use the caption tag (http://www.w3schools.com/tags/tag_caption.asp / https://developer.mozilla.org/en-US/docs/Web/HTML/Element/caption) This element is meant for this purpose. It behaves like a div, but doesn't span the entire width of the parent of the table (like a div would do in the same position (don't try this at home!)), instead, it spans the width of the table. There are some cross-browser issues with borders and such (was acceptable for me). Anyways, you can make it look as a cell that spans all columns. Within, you can make rows by adding div-elements. I'm not sure if you can insert it in between tr-elements, but that would be a hack I guess (so not recommended). Another option would be messing around with floating divs, but that is yuck!

Do

<table>
    <caption style="gimme some style!"><!-- Title of table --></caption>
    <thead><!-- ... --></thead>
    <tbody><!-- ... --></tbody>
</table>

Don't

<div>
    <div style="float: left;/* extra styling /*"><!-- Title of table --></div>
    <table>
        <thead><!-- ... --></thead>
        <tbody><!-- ... --></tbody>
    </table>
    <div style="clear: both"></div>
</div>

According to the specification colspan="0" should result in a table width td.

However, this is only true if your table has a width! A table may contain rows of different widths. So, the only case that the renderer knows the width of the table if you define a colgroup! Otherwise, result of colspan="0" is indeterminable...

http://www.w3.org/TR/REC-html40/struct/tables.html#adef-colspan

I cannot test it on older browsers, but this is part of specification since 4.0...


try using "colSpan" instead of "colspan". IE likes the camelBack version...


Another working but ugly solution : colspan="100", where 100 is a value larger than total columns you need to colspan.

According to the W3C, the colspan="0" option is valid only with COLGROUP tag.


Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to html-table

Table column sizing DataTables: Cannot read property 'length' of undefined TypeError: a bytes-like object is required, not 'str' in python and CSV How to get the <td> in HTML tables to fit content, and let a specific <td> fill in the rest How to stick table header(thead) on top while scrolling down the table rows with fixed header(navbar) in bootstrap 3? Sorting table rows according to table header column using javascript or jquery How to make background of table cell transparent How to auto adjust table td width from the content bootstrap responsive table content wrapping How to print table using Javascript?

Examples related to tablelayout

How is a CSS "display: table-column" supposed to work? Multiline TextView in Android? Set equal width of columns in table layout in Android CSS: Truncate table cells, but fit as much as possible Can a table row expand and close? How can I create a table with borders in Android? How do you specify table padding in CSS? ( table, not cell padding ) Colspan all columns