Tadej Gašparovič Tadej Gašparovič - 1 month ago 15
CSS Question

CSS - Responsive Image Size

I am trying to make all images have

max-width: 400px;
and at the same time be responsive i.e. mobile friendly.

The following styling did make the images responsive, but
max-width: 100%;
is making the images vary in size a lot more than wanted thus this is not a suitable solution.

max-width: 100%;
Width: auto;
height: auto;
border: 1px #DFDFDF solid; /* Just to make the image look nicer */


What I need is something along these lines (but responsive):

max-width: 400px;
width: auto;
height: auto;
border: 1px #DFDFDF solid; /* Just to make the image look nicer */


I've tried many different things, but I just can't get it to work.

Thank you for your help!

Lee Lee
Answer

By default, your images want to be the width of the parent, but you want to cap that width to not go above 400px.

max-width: 400px;
width: 100%;
height: auto;
border: 1px #DFDFDF solid; /* Just to make the image look nicer */

To be a bit more in depth and have more control, you could split this out and use a media query to target your mobile display:

// Desktop
.your-img {
    max-width:400px;
    width:100%;
    height:auto;
    border:1px solid #dfdfdf;
}

// Mobile
@media (max-width:768px) {
    .your-img {
        width:auto;     // Get the original width of the image
        max-width:100%; // So the image can only be as wide as the device max
        display:block;  // Image becomes a block element
        margin:0 auto;  // Centre image if smaller than device width
    }
}