David Jones
David Jones

Reputation: 10219

Using a table to lay out a grid of squares with fixed spacing where the width of each square is a percentage of the screen width

I'm laying out a simple grid of squares where the width of each square is 50% of the screen width and there's a fixed amount of spacing between each square. I've found a very intuitive way to do this using tables and one line of JavaScript (here's a fiddle):

HTML

<table width="100%" cellspacing="10">
  <tr>
    <td width="50%"></td>
    <td width="50%"></td>
  </tr>
  <tr>
    <td width="50%"></td>
    <td width="50%"></td>
  </tr>
</table>

JavaScript

$('td').height($('td').width());

This seems like a sane, semantic use of tables, but I'm almost certain I would be ripped apart by my fellow programmers for using tables for anything but tabular textual data. Is there any valid reason not to use the approach outlined above?

Upvotes: 1

Views: 260

Answers (1)

MarcoK
MarcoK

Reputation: 6110

When your HTML is going to contain tabular data, I don't think it's a problem to use tables. If you're using a table just to design your layout, you should go with "normal" elements (div, section, article etc.).

But, what I do want to point out, is that you're using layout-styles inside your HTML - now that's wrong. You should place your design inside CSS, and keep your HTML clean. Example:

HTML

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

CSS

table {
    width:100%;
    border-collapse: seperate;
    border-spacing : 10px;
}
td {
    width:50%;
    background-color:red;
}

jQuery

$('td').height($('td').width());

JSFiddle.

Upvotes: 1

Related Questions