I need to align a text under an image, thus the text should not exceed the image width.
However the images are random, they are chosen in php and they do not have the same height and width.
I found many solutions but all of them involve setting a fixed width to the container which is something that I can’t do since the image size can vary.
Here is my code so far without an width on the container:
.container {
position: relative;
}
.reward-complete-image {
max-width: 70vw;
max-height: 70vh;
}
<div class="container">
<figure>
<img class="reward-complete-image" src="https://wallpapercave.com/wp/bvJq0ra.jpg">
<figcaption>This picture can change it is dynamically generated, thus other images could have a different width and height. This is why the solution should allow for the text under the image to be ".</figcaption>
</figure>
</div>
The existing CSS if for other reasons, you can change it if needed.
I used figure and ficaption but feel free to use other older tags if you prefer.
I tried to apply a width in percentage to the container, or a max-width in percentage or fixed number of pixels, but all this does not work, the text goes still beyond the image.
I prefer to use only HTML and CSS, without Javascript if possible. I also put the existing html in a table in one column but the text still goes beyond the image.
How can I align the text under the image without knowing the width and the height of the image upfront?
Thank you
2
Answers
You can try using a grid layout that adjusts to the size of your image automatically. Like so:
If you want the text width to be the same as the given image, then add
display: table-caption;
tofigure
, like this: