使响应式图像适合父容器

时间:2013-11-04 23:31:13

标签: html css

我一直在试图弄清楚是否有一个纯CSS解决方案,以确保我的横幅中的图像不会低于父级的高度,但保持图像的比例。

您可以在此处查看演示: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%;
}

我的目标是使图像始终为100%,但高度不低于300px。这意味着图像截止,但没关系,我只是想知道是否有纯CSS解决方案,或者我是否需要使用jQuery

4 个答案:

答案 0 :(得分:21)

而不是使用&lt; img&gt;标签,我将该图像作为div的背景图像,并给它以下样式:

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

这是我使用的小提琴:http://jsfiddle.net/MathiasaurusRex/LkxYU/4/

这是完整的HTML和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;
}

答案 1 :(得分:1)

根据屏幕尺寸,您的图片将不可避免地超出比例,为什么不尝试背景图片:

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

或者您可以为图片代码添加最大高度:

.banner_holder img{
  width: 100%;
  max-height: 300px;
}

答案 2 :(得分:0)

尝试:

.banner_holder img{
height: 100%;
/* OR */
height: inherit;
}

答案 3 :(得分:0)

使用max-height和max-width确保图像始终适合父div:

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

.banner_holder img{
    max-width: 100%;
    max-height: 100%;
}

编辑:对不起,我想念你写过关于300px截止东西的部分:) MathiasaurusRex的答案是正确的。

相关问题