I want everything on my website to be aligned to a grid, but I was at first unable to figure out how to do this nicely for images. I set a fixed height for images, but this looked bad.
The specific constraints were:
- The image needs to take up 100% of the width of the parent container.
- The image needs to maintain its aspect ratio.
- The image should have as little empty space as possible around it.
- Items around the image should still be aligned to the grid.
I spent a long time trying to find a way to do this, without success. The main problem is that when you're calculating the new height of the image, you don't have access to the width of the parent.
After some help in my server, I was able to find
a solution. In order for this solution to work, we
must first embed the aspect ratio of the image into
the image's style
attribute in the HTML
code. For example:
<figure>
<img src="20250516012109_crowd.jpg" style="--ratio:calc(4032/1794)" alt="The crowded showcase area in the Garage on the first day. My game no signal is partially visible at the bottom.">
</figure>
Next, we need to set the parent of the image to
have container-type: inline-size
, which
allows us to access the cqi
unit. This
is how we're able to get the width of the parent
while calculating the height. Our CSS will then look
something like this:
:has(> img) {
figurecontainer-type: inline-size;
img {width: 100%;
height: round(up, calc(100cqi / var(--ratio)), var(--grid-size));
object-fit: contain;
} }