Forum:Gallery template

Hi, I'd like to hear some suggestion about which is the best way to make a "gallery template". I'm currently using templates like this one, basically simply a table, but I want to make a generic template which I'll use to make these kind of galleries. My idea was to use a pair of template that in the end have a structure like this one:

Each cell is composed by an image and a caption, so I tried making the elements nested tables of the mother table with these templates (1 and 2, which give this result, the standard way is shown above it). My problem is that I want the nested tables/elements to be displayed inline so that an element will be shown in a new row when there is no more space left, now I'm making the rows every 5 elements, I want it automatic because, for example, in monobook the table can be wider. I tried to make divs instead nested tables, but it either show all elements in a single row or make a new row for each of them. Any ideas?