简体   繁体   English

如何在使用精灵时裁剪背景图像

[英]How to crop a background image when using sprite

here is the file : http://studioteknik.ca/stackoverflow_question/test1.html i need to see only one background image at the time, let's say the second. 这是文件: http//studioteknik.ca/stackoverflow_question/test1.html我需要在当时只看到一个背景图像,让我们说第二个。 It's 400 pixel from the top, but i need it image to be crop top 400 height. 这是从顶部400像素,但我需要它的图像是裁剪前400高度。 HOW TO DO THAT ? 怎么做 ?

In general content images should not be backgrounds or sprites, they should be inline images using the IMG tag. 一般来说, 内容图像不应该是背景或精灵,它们应该是使用IMG标签的内嵌图像。 Sprites are usually reserved for UI elements such as icons and menu elements. 精灵通常保留用于UI元素,如图标和菜单元素。

<div class="sprite1"></div>

CSS: CSS:

.sprite1 { 
        height:400px;
        width:400px;
        background-image:url(http://www.studioteknik.ca/stada/wp-content/themes/stada-theme/images/banner_sprite.jpg);
        background-position:0 -400px; 
    }

Yes - that's a good answer. 是的 - 这是一个很好的答案。 Generally, you position a sprite exactly the way you would position a normal image, but set the height and width so that they only cover one portion of it. 通常,您精确定位精灵与定位普通图像的方式相同,但设置高度和宽度以便它们仅覆盖它的一部分。 The background position is the only thing that changes. 背景位置是唯一改变的。 If I had a 40 pixel high sprite and wanted to display it has 2 20px high images, the code would be this: 如果我有一个40像素的高精灵,想要显示它有2个20像素高的图像,代码将是这样的:

  .sprite1{ height:20px;
 width:20px;
 background-image:url("myimage.jpg");
  background-position: 0 0;
 }

.sprite2{
height:20px;
width:20px;
background-image:url("myimage.jpg");
background-position:0 -20;
}

I use a pseudo element (before/after) to generate the box size I want for the sprite and add the background-image to that. 我使用一个伪元素(之前/之后)生成我想要的精灵盒子大小,并添加背景图像。

That way you can set the 'normal' element to position: relative and the :after to position: absolute; 这样你可以将'normal'元素设置为position: relative:after to position: absolute; .

Then position the after as you want it in relation to the main container and the size of the after element prevents any more of the image sprite 'bleeding out'. 然后根据需要将after放置在主容器的位置,after元素的大小可以防止更多的图像精灵“流血”。

I documented that technique more fully here: http://benfrain.com/image-sprites-data-uris-icon-fonts-v-svgs/ 我在这里更全面地记录了这种技术: http//benfrain.com/image-sprites-data-uris-icon-fonts-v-svgs/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM