Skip to content Skip to sidebar Skip to footer

How Can I Resize A Background-image To Fit My Element (without Set Width) In CSS 2?

My problem is that I have to remain compliant with IE 8, so no CSS3 only answers will do. I know that I can use the background-image property, but I can't use background-size prope

Solution 1:

You can do this quite simply:

html:

<div class="holder">
    <img src="http://www.lorempixel.com/400/200/" />
    <div class="text">Testing text</div>
</div>

css:

.holder {position:relative; width:100%; overflow:hidden;} //this has overflow hidden so it treats the image like a background and hides any extra
.holder img {position:absolute; left:0; top:0; width:100%; z-index:1;}
.holder .text {position:relative; z-index:2; text-align:center;} //this is positioned relative so the div grows to the size of the text

http://jsfiddle.net/UANFm/2/


Solution 2:

Very tough without javascript.

You might be able to add it as a normal image, set the postition to relative and z-index it under all the other content, then set width 100%. But this is still a bit of a hackish way and one that I haven't tested.

Edit try this: http://jsfiddle.net/xTgCY/

<div class="wrapper">
    <img src="http://t2.gstatic.com/images?q=tbn:ANd9GcSaATzueHSd2rQXCWUQXFXc1sFAx3tNXBj-px5bU64D4ji5rmF6cw">
        <div class="content">aihadfuigh iaghdf aoisyhif o[iayhdf oiahdfio sadf</div>
</div>

.wrapper {
    width: 300px;
    position: relative;
}
.wrapper img {
    position: relative;
    z-index: -5;
    width: 100%;
}
.content {
   position: absolute;
   z-index: 0;
   top: 0;
    left: 0;
    width: 100%;
}

Post a Comment for "How Can I Resize A Background-image To Fit My Element (without Set Width) In CSS 2?"