使img响应并填入div [英] make img responsive and fill into a div

查看:148
本文介绍了使img响应并填入div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有定义的宽度和高度的div。然后我有一张我想要的照片(保持比例)。像那样:

 < div style =width:200px; height:300px; background:red;> 
< div style =display:inline-block; max-width:100%; max-height:100%; background:blue;>
< img src =http://placehold.it/200x800style =width:auto; height:auto; max-width:inherit; max-height:inherit/>

< / div>
< / div>

结果是错误的,导致img覆盖在div上。我希望img像第一个示例中那样调整大小。






I have a div with a defined width and height. Then I have an image which I want to fit on it (keeping proportions). Like that JsFiddle :

<div style="width: 200px; height: 300px; background: red;">
    <img src="http://placehold.it/200x800" style="width: auto; height: auto; max-width: 100%; max-height: 100%" />
</div>

Now I want a div wrapped on the img (that is ajusted exactly to the img width and height and position) because then want to have some elements inside the div with position:absolute relatively to the img. Check on JsFiddle:

<div style="width: 200px; height: 300px; background: red;">
    <div style="display: inline-block; max-width: 100%; max-height: 100%; background: blue;">
                <img src="http://placehold.it/200x800" style="width: auto; height: auto; max-width: inherit; max-height: inherit" />

    </div>
</div>

The result is wrong, cause the img is overlayed on the div. I want the img to resize like in the first example.

In Child with max-height: 100% overflows parent they pointed out that the div needs to have a height and a width, but then the div will not be filling the whole img.

There is actually a way to do it?

My whole layout is more complex and totally responsive with flex on top and the example here is just an approximation focused on the issue I have. So any solution with fixed height and width will be wrong.

解决方案

Don't use an extra div. Just use a background-image. Cleaner, easier, more semantic. Can position things absolutely on the one wrapper div.

CSS:

.wrapper {
  width: 200px; 
  height: 300px; 
  background: url('http://placehold.it/200x800'), red; 
  background-size: auto 100%;
  background-repeat: no-repeat;
}

HTML:

<div class="wrapper"></div>

Demo

Alternatively, if you're dead set on having an extra div, you can accomplish the same effect like this:

CSS:

.wrapper {
    width: 200px; 
    height: 300px;
    background: red;
}

.inner-wrapper {
    width: 0;
    height: 100%;
}

.inner-wrapper img {
    height: 100%;
}

HTML:

<div class="wrapper">
    <div class="inner-wrapper">
        <img src="http://placehold.it/200x800">
    </div>
</div>

Demo

这篇关于使img响应并填入div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆