CSS Sprite + background-size:封面

时间:2017-08-09 15:58:26

标签: html css sprite cover

有没有办法在使用CSS Sprite加载的图片上使用 background-size:cover ?示例代码:

[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}
...

1 个答案:

答案 0 :(得分:5)

你需要根据图像中的精灵数量使用%作为背景大小和背景位置:

下面带有3个精灵图像的例子:(可以调整第一个div的大小,然后查看精灵拉伸)



  div {
  resize: both;
  background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJYAAAAyCAMAAACJUtIoAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA2ZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYxIDY0LjE0MDk0OSwgMjAxMC8xMi8wNy0xMDo1NzowMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDpFNDI3Q0MzNjFEN0RFNzExQUQwMzhERDMyREMwRDFBOSIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDo2Njg5QjY3NjdEMUQxMUU3OTExOEI2N0ZGOTY1NzY2OCIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDo2Njg5QjY3NTdEMUQxMUU3OTExOEI2N0ZGOTY1NzY2OCIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ1M1LjEgV2luZG93cyI+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>
&#13;
&#13;
&#13;

连续3个精灵使background-size: 300% 100%;显示三分之一。

如果在行中设置了精灵,请执行background-size: 100% 300%;

如果精灵是3行3 col然后是background-size: 300% 300%;

等等。