简体   繁体   中英

CSS Sprite + background-size:cover

Is there a way to use background-size:cover on images loaded with CSS Sprite? Example code:

[class*='img-sprite-']{
   background-image:url('../images/sprite/img.png');
   background-repeat:no-repeat;
   display:block
}

.img-sprite-a1{background-position:-5px 5px}
.img-sprite-a2{background-position:-10px 10px}
.img-sprite-a3{background-position:-15px 15px}
...

you need to use % according to number of sprites within image for background-size and background-position:

example below with a 3 sprites image: (first div can be resized to play with and see sprite stretching)

  div { resize: both; background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJYAAAAyCAMAAACJUtIoAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA2ZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8++IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOkU0MjdDQzM2MUQ3REU3MTFBRDAzOEREMzJEQzBEMUE5IiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOkU0MjdDQzM2MUQ3REU3MTFBRDAzOEREMzJEQzBEMUE5Ii8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+h3SaNAAAAAZQTFRFKCgo////2hH7kgAAAAJ0Uk5T/wDltzBKAAABGklEQVR42uzZSxKEIBAD0PT9Lz27WVjaJOkGKZU1GR4y8hOxZcFzWfiXtgDytNIEK2MCyOOyahyhAsjjumqU4QLI44ZqEOICyNOOqsOFPMqxpNRZABSL/v8eK5GduexYyhJfqxi3wj7vhKXNQocqKitIljw5xsfalGX8/gJWuCxMZHndNlMsy26gcwxra2J1DNU1scYSd6jtO4jKw/L2WwZLG0Jvd/oYln36wQqWfoqb+iaiMOzzWOhdrZpZ9ol8DsvdCF011MPyVbuyzltqYVVU81gl1dtYNdUsVo/qJSzj2mHBLG8dwcaLdReLvnk7vxFrZkFlkdVrLDSxYktW86YZOou8yV/POsZCOflMLpVvPjeWj6WUnwADAPW9F+6UuMBmAAAAAElFTkSuQmCC) orange no-repeat; color: white; padding: 2em; } .demo { min-height: 50px; background-size: 300% 90%; background-position: 50% 0; display: inline-block; overflow: scroll; 
 <div class="demo">resize me</div> <div>my sprite</div> 

3 sprites in a row makes background-size: 300% 100%; to show horizontaly a third of it.

If sprites are set in rows, then do background-size: 100% 300%; ,

if sprites are 3 rows of 3 col then background-size: 300% 300%;

and so on.

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