Search code examples
htmlcssheightstylesheet

How to fit image to div without using javascript


I want to make my image fit into a div without using any javascript and without letting the image stretch. I am unable to use the background-image property as I am using css transitions. Using

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

Works and is exactly what I want to do except for the scenario when the image is too small. I have considered enlarging the image to a certain height while maintaining the width and then applying max-height and max-width but this seems like a very hacky, time expensive solution if it even works at all. Are there any other suggestions?

Thanks

Kabeer


Solution

  • Display the image as block and it will fit to the parent container

    wrap the image in a container and set this style for the image in it:

    img {
        display: block;
        max-width: 100%;
        max-height: 100%;
    }
    

    so it won't strech

    here you have a fiddle
    This fiddle is with smaller image than the container