Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

html - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 fiddle 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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...