剪辑/裁剪背景图像与CSS

Dah*_*hie 67 css css-sprites

我有这个HTML:

<div id="graphic">lorem ipsum</div>
Run Code Online (Sandbox Code Playgroud)

用这个CSS:

#graphic { background-image: url(image.jpg); width: 200px; height: 100px;}
Run Code Online (Sandbox Code Playgroud)

我正在应用的背景图像是200x100像素,但我只想显示200x50像素的背景图像的裁剪部分.

background-clip似乎不是正确的CSS属性.我可以用什么呢?

background-position 不应该使用,因为我在精灵上下文中使用上面的CSS,其中我想要显示的图像部分小于定义CSS的元素.

Bre*_*ent 94

您可以将图形放在具有自己的维度上下文的伪元素中:

#graphic {
  position: relative;
  width: 200px;
  height: 100px;
}
#graphic::before {
  position: absolute;
  content: '';
  z-index: -1;
  width: 200px;
  height: 50px;
  background-image: url(image.jpg);
}
Run Code Online (Sandbox Code Playgroud)

#graphic {
    width: 200px;
    height: 100px;
    position: relative;
}
#graphic::before {
    content: '';
    
    position: absolute;
    width: 200px;
    height: 50px;
    z-index: -1;
    
    background-image: url(http://placehold.it/500x500/); /* Image is 500px by 500px, but only 200px by 50px is showing. */
}
Run Code Online (Sandbox Code Playgroud)
<div id="graphic">lorem ipsum</div>
Run Code Online (Sandbox Code Playgroud)

浏览器支持很好,但如果您需要支持IE8,请使用单个冒号:before.IE在此之前的版本中不支持任何语法.

  • 对于不熟悉伪元素如何呈现的人来说,浏览器会将它们放置在您要定位的元素的 html 中。我这样说是为了让您不必花很长的时间来了解它如何不适用于没有内部 html 的输入字段等元素。 (2认同)

san*_*eep 9

也许你可以像这样写:

#graphic { 
 background-image: url(image.jpg); 
 background-position: 0 -50px; 
 width: 200px; 
 height: 100px;
}
Run Code Online (Sandbox Code Playgroud)