I have a blog that uses images with different scales and aspect ratios. Some are short and wide, some are tall and narrow. You can see an example here.
I want my images to:
- Be at most as wide as the post (no larger than 100% width of their container), so that when an image is wide and short, it fills 100% of the width of the post.
- Be at most 350px tall, so that when an image is tall and narrow, it's size is restricted by its height - it will be 350px tall, and centered in the middle of the post.
Like so:
To accomplish that with a regular img
tag I use the following css:
img {
display: block;
max-width: 100%;
max-height: 350px; // to restrict the height of tall narrow images
margin: auto; // to center the tall narrow images when their width is less than 100%
}
Now I want to automatically scale down and optimize my images with next-image
, but I can't seem to find the right combination of styles and parameters to accomplish the same effect.
When I set layout="responsive"
, the image always fills 100% of the width of the container, ignoring the max-height
paremeter. So if the image is very tall and very narrow, it'll still get stretched to the full with of the post, making it ridiculously tall.
Like so:
When I set layout="fill" objectFit="contain"
I can wrap the images in a container and set container's css to width:100%; height: 350px
. Now it will scale down the tall narrow images to have at most 350px
height, but if the image is very wide and very short, the container will still have the height of 350px (even though it should be much shorter now, because the image is short), which creates vertical space around the image.
Like so:
Can you help me to figure out how to solve this? What should I do to have the equivalent of the css above with next-image?
layout="fill" objectFit="contain"
. Here is a CodeSandbox. – Determine