I am trying to create a responsive grid which shows images and a caption underneath. I am currently trying to use a table to achieve this, although not sure if this is the best method?
What I would like the final product to look like on a device with a smaller screen:
-----
image
-----
caption
-----
image
-----
caption
-----
image
-----
caption
etc...
Then on a larger screen:
----- ----- -----
image image image
----- ----- -----
caption caption caption
etc...
My current HTML (this currently works fine on a large screen but not on a mobile as the whole second row appears underneath the images):
<tr>
<td><img src="img1"></td>
<td><img src="img2"></td>
<td><img src="img3"></td>
</tr>
<tr>
<td><span class="text-caption">Caption 1</span></td>
<td><span class="text-caption">Caption 2</span></td>
<td><span class="text-caption">Caption 3</span></td>
</tr>
Then the CSS:
img {
max-width: 100%;
}
@media only screen and (max-width: 800px){
td {
display: table-row;
}
}
.text-caption {
font-style: italic;
font-size: inherit;
}
I have tried using the jQuery ‘insertAfter’, but that seems a very messy way of doing it as all the elements need a different id and I was struggling to get the code to only execute when screen was below a certain size.
Any help would be greatly appreciated.
3
Answers
For this I definitely wouldn’t use a table, those can get weird sometimes. I’d just make the html layout using sections with a
div
that wraps each caption and image together, and wrap all of those into a containerdiv
and set all of the containers innerdiv
todisplay: inline-block;
which seems to be the functionality you want.simply take a look at what I did here:
You could change it like this:
This could lay it out the way you are trying. The
tells it to make three sections in line.
Then in @media query, you can tell it to line just one section pre line when the screen is small. That is this:
I’d certainly recommend against using a
<table>
element for any kind of layout solution; those days are long past, should never be revisited, and we finally have meaningful solutions for layouts. So, instead, I’d suggest either CSS Grid or Flexbox.My first suggestion will demonstrate CSS Grid, with explanatory comments in the code:
JS Fiddle demo.
With Flexbox:
JS Fiddle demo.
Note, in the flexbox demo, that the last row of the elements may be different than the previous, because of the
justify-content
property-value; this can be adjusted a little if we also useflex-grow: 1
on the child elements, which will allow each of the elements to grow a little into available space; though this can itself lead to an unwanted variation in the appearance:JS Fiddle demo;
References:
align-content
.aspect-ratio
.block-size
.border
.border-radius
.clamp()
.content
.counter
.counter-increment
.counte-reset
.display
.flex-basis
.flex-grow
.flex-shrink
.gap
.inline-size
.inset
.margin
.margin-block
.margin-inline
.object-fit
.padding
.padding-block
.padding-inline
.place-content
.position
.repeat
.