简体   繁体   中英

Resize positioned background image

I have span, and it's styles are represented below. My problem is, it was designed to fill 60px*60px span. But now, I have to make it to fill another span with 50px*50px size. But it can't work with background position, because if i change the background-size, all position slips away. So is there any way (css or javascript hack) to resize an image or a block element with bacground-image after the image has been drawn? I want to avoid rewriting all background positions (I've got classes for each icons like ".entertainment").

<span class="icon icon2 entertainment"></span>

span.icon2 {
 float: left;
 width: 50px;
 height: 50px;
 margin: 5px 0 0 0;
}

#wrapper span.icon.entertainment {
 background-position: -60px -360px;
}

#wrapper span.icon {
 background: url(https://teeg.hu/image/icon.png);
}

Thanks for any help!

There is no pure css solution.

There is a js solution. Resize the background (background-size) as you did, then for each element move the position with the difference between sizes / 2 (in your case 5px).

You don't rewrite the classes, just iterate through elements.

Note: This might become an extensive operation, it is better to rewrite classes, even though that is what you want to avoid (40 is not so much... at most 30 min - testing included).

Ok, I've written some hack. I resized the background:

background-size: 100px 1550px;

and did it with jQuery:

 $(function() {
        $("span.icon2").each(function(index, value) {
            var pos = $(this).css("background-position").split(' ');
            var newPos = [];
            newPos[0] = parseInt(pos[0].replace("px", "")) / 60 * 50;
            newPos[1] = parseInt(pos[1].replace("px", "")) / 60 * 50;
            $(this).css("background-position", newPos[0] + "px " + newPos[1] + "px");
        });
    });

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