Search code examples
javascriptjqueryhtmlcsstabular

jQuery align table (number of rows/cells) based on screen resolution


I have a table like this (8 cells only for illustrative purposes, may be more or less):

[1] [2] [3] [4]
[5] [6] [7] [8]

Each item in each cell is roughly 450px wide, so they fit comfortably next to each other on a 1920x1200 screen (which, incidentially, is mine). However, I need this configuration to change automatically and align the best possible way in case somebody with a smaller (or wider) screen resolution comes along, or resizes the browser window.

So, for 1024x768 it would be:

[1] [2]
[3] [4]
(etc)

and for 2560x1600 it would be:

[1] [2] [3] [4] [5]
[6] [7] [8] [9] [10]
(etc)

How can I do something like this - maybe with jQuery or CSS?


Solution

  • Instead of using a table use an unordered list. Ensure that the width of the unordered list itself (or perhaps its container) is a percentage width (it will scale to the size of the browser window). Float each of the <li> elements and specify a width if you want them equal size. The browser will do the rest for you.

    Example:

    HTML:
    <ul id="mydata">
      <li>1</li>
      <li>2</li>
      <li>3</li>
    </ul>
    
    CSS:
    ul#mydata { width: 90%; }
      ul#mydata li { width: 450px; float: left; } /* Don't *have* to specify width */