Creating a cohesive image gallery with captioned images of different aspect ratios is my goal. To maintain consistency, I desire the browser to display each image at the same height while preserving its original aspect ratio by adjusting the width accordingly. However, I am facing difficulty in ensuring that the width of the caption matches the width of the image.
The structure of my HTML code is as follows:
<div class="photo">
<a href="images/name.jpg">
<img src="thumbs/name.jpg">
</a>
<div class="caption">Imagine long caption here</div>
</div>
This is one of several CSS attempts I have made:
div.photo {
margin: 5px;
float: left;
height: 7cm;
margin-bottom: 3cm;
}
div.photo img {
display: block;
max-height: 7cm;
width: auto;
}
div.caption {
padding: 15px;
text-align: center;
display : block;
width: 90%;
overflow : auto;
}
Here are the objectives I believe I have achieved:
Setting a fixed height for the
photo
element ensures uniformity in height.The bottom margin on the
photo
element accommodates space for the caption.Using
max-height
andwidth: auto
for the image maintains its aspect ratio.Applying
text-align
anddisplay
properties to the caption centers it and wraps the text correctly.
However, I am encountering an issue:
- Many captions appear wider than their respective photos due to the
photo
element expanding, especially when dealing with "narrow portrait" 9:16 aspect ratio photos.
I want to avoid manually determining and setting the width of each element based on the image's aspect ratio. Is there a CSS solution to automatically adjust the width of an element to match the width of an image contained within a descendant?