Search code examples
htmlcssimageresponsiveimage-resizing

CSS / HTML - Auto resize images to screen size


I'm trying to create a responsive web site. For that I found a nice looking template and adjusted it according to my needs.
One thing however came up where I couldn't find a solution so far - and that is resizing of images with different dimensions.
Let's say I have an image with a width of 600px and one with a width of 500px. My screen size is 700px. I want both images to be shown at their native width (600px & 500px). Now I reduce my screensize to 550px. I want the 600px image to be resized to 550px. No changes to the 500px image because the native width is still smaller than the screen. Now I reduce the screensize to 400px. Both images should now also be reduced to 400px accordingly.
I've been googling and reading here for hours but could not find an automatic solution for this.
Best thing I found is is setting <img style="width:100%;max-width:xxx px;" where xxx is the original width of the image. But... I'd have to do this manually for each and every image!
Without max-width the image would always be strechted to 100% of the screen size.
As an alternative I found some JavaScript that calculates the original width of the image and could be used to fill out the max-width value.
If someone disables JavaScript (EG by using NoScript browser adddon) the whole thing wouldn't work.
Since I'm printing out my website using Perl I could do the calculation with Perl as well. That would help against disabled JavaScript. But still...
Are there really no better solutions? Do I really have to calculate the max-width for each and every image?

Here's the current work-in-progress: https://www.digioso.org/html5up-striped
The template features an image fit class that basically sets the width to 100% of the container and then I added the same image using width=100%;max-width=400px .
The image fit makes the image always use 100% of the screen which I don't want.

Thanks a lot!


Solution

  • Do not apply an explicit width or height to the image tag. Instead, give it:

    max-width:100%;
    max-height:100%;
    

    check: How do I auto-resize an image to fit a 'div' container?