htmlcss

Make responsive image fit parent container


I've been trying to figure out if there is a pure CSS solution to ensure the image within my banner doesn't go below the height of the parent but keep ratio of the image.

You can see a demo here: http://jsfiddle.net/LkxYU/1/

html:

<div class="banner_holder">
    <img src="http://placekitten.com/g/800/600"/>    
</div>

css:

.banner_holder{
    width: 100%;
    height: 300px;
    min-height: 200px;
    position: relative;
    outline:1px dotted red;
}

.banner_holder img{
    width: 100%;
}

My aim is to have the image always 100%, but never below 300px in height. This would mean image cutoff, but thats fine, i just want to know if there is a pure CSS solution, or if i need to use jQuery


Solution

  • Instead of using an <img> tag, I made that image the background-image for a div and gave it the following styles:

    .banner_holderImage{
        height: 100%;
        position:relative;
        background: url("http://placekitten.com/g/800/600")no-repeat;
        background-size: cover;
        background-position: center;
    }
    

    Here's the JSFiddle I was using: http://jsfiddle.net/MathiasaurusRex/LkxYU/4/

    Here's the complete HTML and CSS:

    <div class="banner_holder">
        <div class="banner_holderImage"></div>  
    </div>
    
    .banner_holder{
        width: 100%;
        height: 300px;
        min-height: 200px;
        position: relative;
        outline:1px dotted red;
    }
    .banner_holderImage{
        height: 100%;
        position:relative;
        background: url("http://placekitten.com/g/800/600")no-repeat;
        background-size: cover;
        background-position: center;
    }