Friday, February 8, 2013

Table border with CSS

I want to have a one-pixel one-color solid border around a table and its cells. Adding border="1" to the table tag isn't suitable, because it looks horrific in most of the browsers.

Solution with HTML only

Back in the old days we used to use just HTML to create a one-pixel border. Some people even used 1×1 pixel transparent gifs, but let’s not go into that. The easiest way to achieve the border was to use nested tables: outer table that provides the border color and inner table that holds the content.

    <table border="0" cellspacing="0" cellpadding="0">
        <td bgcolor="#FFFFCC">Cell 1</td>
        <td bgcolor="#FFFFCC">Cell 2</td>
        <td bgcolor="#FFFFCC">Cell 3</td>
        <td bgcolor="#FFFFCC">Cell 4</td>

This is all we have. Really. Everything else is hidden in a style sheet. You can easily change the looks of your table without touching the HTML.

Maybe the first thing that comes up to your mind when you start creating a style sheet for a table border is to add a one-pixel border to every table cell. However, that would cause the borders to "duplicate" between the cells. The trick is to let cells to have only the top and right borders and add the bottom and left borders to the table. This way it looks like every cell is surrounded with a border, even though technically this is not the case.

Here is our final code:
<style type="text/css">
/* <![CDATA[ */

table, td
    border-color: #600;
    border-style: solid;

    border-width: 0 0 1px 1px;
    border-spacing: 0;
    border-collapse: collapse;

    margin: 0;
    padding: 4px;
    border-width: 1px 1px 0 0;
    background-color: #FFC;

/* ]]> */

    <td>Cell 1</td>
    <td>Cell 2</td>
    <td>Cell 3</td>
    <td>Cell 4</td>

No comments:

Post a Comment

your comments.....