有没有一种方法可以在加载有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}
...
最佳答案
您需要根据图像中 Sprite 的数量使用%作为背景尺寸和背景位置:
下面的示例带有3个 Sprite 图像:(可以调整第一个div的大小以播放并查看 Sprite 拉伸(stretch))
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>
连续3个 Sprite 使
background-size: 300% 100%;
可以水平显示其三分之一。如果将 Sprite 排成一行,则执行
background-size: 100% 300%;
,如果 Sprite 是3行,每行3列,则
background-size: 300% 300%;
等等。
关于html - CSS Sprite +背景大小:cover,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45595520/