I encountered a unique issue that needed a creative solution. My goal was to showcase all images in their original size without constraints on aspect ratio, alignment, or additional HTML elements, while also ensuring they do not exceed a specified maximum width in pixels. If the viewport is smaller than this designated size, the images should dynamically adjust. Simply setting a width
property would not suffice for my requirements.
Building upon @Kiaurutis' suggestion:
img {
max-width: 400px;
}
@media (max-width: 400px) {
img {
max-width: 100%;
}
}
You can see a functional demonstration here: https://jsfiddle.net/vrehxmpx/. In the provided example, an image larger than 400px will always scale down accordingly, while an image smaller than the threshold will only resize if the screen reduces below the image's dimensions.
To account for margins, borders, and other decorative elements surrounding the image, simply modify the @media
's max-width
value.