Background image stretch y-axis only, keep repeat-x

Idan Shechter picture Idan Shechter · Mar 1, 2013 · Viewed 52.6k times · Source

I have an image set as a background image of a div. The DIV size is changing and inside their is the image which is a gradient.

CSS:

#scroller_shadow{
    background-image:url(../img/ui/shadow.png);
    background-repeat:repeat-x;   
    background-position:top;
}

I need a cross-browser solution for making the image fit the height of the div in the y-axis only, keeping the repeat-x. The DIV is being resized dynamically via JQuery.

Their might be a cross-browser option using JQuery. I don't mind using scripts to achieve that in order to get cross-browser support (IE7+). I don't want to stretch the image because it loses the intensity when you stretch the image on the x-axis, making a semi-transparent png image almost transparent.

Thanks.

Answer

Charlotte picture Charlotte · Mar 1, 2013

I had this problem too. It's easy in most browsers, but IE8 and below it's tricky.

Solution for modern (anything not IE8 and below) browsers:

#scroller_shadow {
    background: url(../img/ui/shadow.png) center repeat-x;
    background-size: auto 100%;
}

There are jQuery plugins that can mimic background-size for IE8 and below, specifically backgroundSize.js but it doesn't work if you want it to repeat.

Anyways thus begins my terrible hack:

<div id="scroller_shadow">
    <div id="scroller_shadow_tile">
        <img src="./img/ui/shadow.png" alt="" >
        <img src="./img/ui/shadow.png" alt="" >
        <img src="./img/ui/shadow.png" alt="" >
        ...
        <img src="./img/ui/shadow.png" alt="" >
    </div>
</div>

Make sure to include enough <img>'s to cover the area needed.

CSS:

#scroller_shadow {
    width: 500px; /* whatever your width is */
    height: 100px; /* whatever your height is */
    overflow: hidden;
}

#scroller_shadow_tile {
    /* Something sufficiently large, you only to make it unreasonably wide if the width of the parent is dynamic. */
    width: 9999px;
    height: 100%;
}

#scroller_shadow_tile img {
    height: 100%;
    float: left;
    width: auto;
}

Anyways, the idea is to create the stretch effect from the images.

JSFiddle.