简体   繁体   中英

Image height in IE7

I've been trying to create a stretchable background image by absolutely positioning an img tag and giving it a width and a height of 100% as so:

<div class="item">
    <div class="background">
        <img src="http://placehold.it/100x100" width="100%" height="100%" style="width: 100%; height: 100%; border: 1px solid green;" />
    </div>
    <span class="text">
        aaa bbb ccc ddd
    </span>
</div>

This works fine in IE8+, Chrome and Firefox, but unfortunately I need to support IE 7 as well.

This JSFiddle demonstrates the problem: The image is resized to fit 100% width, but its aspect ratio is preserved, as such:

截图

How do I cause the image to be exactly the same size as the containing div? Note that if I give the containing div ( .background ) a fixed size, the problem is resolved, but that defeats the purpose of having it resized according to the text.

You need to set the height (and width, prolly) on the containing div as well, not just the image:

.background {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width:100%;
    height:100%; /*This is the important bit */
}

http://jsfiddle.net/zPcwC/9/

Also, proving that it still works when the text fills up:

http://jsfiddle.net/zPcwC/10/

See: http://jsfiddle.net/cqTTm/

Tested in IE7/8/9, Firefox, Chrome, Safari, Opera.

The *property rules are only applied to IE7.

.item {
    position: relative;
    display: inline-block;
    *display: inline;
    zoom: 1;
}
.background {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    *height: 100%
}
.text {
    position: relative;
}

On .background , plain height: 100% might be usable instead of *height: 100% . I left it applying to the only browser that needs it (IE7) to avoid having to retest in all those browsers again.

Why don't you just do this?

<div class="item">
  <div class="background">
    aaa bbb ccc ddd
  </div>
</div>

Then, in your css, you could put

.background {
  background: transparent url(placeholder.jpg) no-repeat top left;
}

This way, the image is fixed as a background image in the .background div. The content within the background div will stretch it, reveiling only a part of the background image.

Is this what you are asking?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM