Setting table column widths non-intrusively using CSS and JQuery

Below is a Javascript snipped which will mark each table cell with a CSS class containing the column number. This allows you to set the table column widths using just one CSS rule and without hand editing the table HTML code. This is to workaround the lack of nth-child pseudoclass CSS selector in IE6, IE7 and IE8 – there is no direct Internet Explorer compatible way to set table column widths from CSS.

This was originally created to workaround the limitation of Kupu : one couldn’t set table column widths from WYSIWYG editor. Instead, the content editor has predefined table classes and column width sets.

The code is also available in the snipplr.

/*  Add column index pseudoclasses to table cells.

    A JQuery snippet to be executed after DOM model has been loaded.

    Each table cell will be marked with a CSS class containing the cell's column number.
    This is to workaround the lack of nth-child pseudoclass CSS selector support in
    IE6, IE7 and IE8.

    Read this sad fact sheet:

    http://msdn.microsoft.com/en-us/library/cc351024(VS.85).aspx

    This way we can style table columns without explicitly settings classes
    for each cell in WYSIWYG editor.

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

    will become

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

    Both <tbody><td> and <thead><th> elements will be fixed.

    Use the following CSS to style tables:

    table.course-schedule-table .column-1 {
        width: auto;
    }

    table.course-schedule-table .column-2 {
        width: 150px;
    }

    table.course-schedule-table .column-3 {
        width: 150px;
    }

    @author Mikko Ohtamaa

    @license 3-clause BSD

    http://www.twinapex.com

*/

function createTableColumnPseudoClasses() {

    jq("tr").each( function()  {
        var counter = 1;
        jq(this).children("td,th").each( function()  {
            jq(this).addClass("column-" + counter);
            counter++;
        });
    });
}

// Run code on document load
jq(createTableColumnPseudoClasses);

Leave a Reply

Your email address will not be published. Required fields are marked *