CSS

使用CSS剪辑/裁剪背景图像

发布于 2021-02-02 16:39:01

我有这个HTML:

<div id="graphic">lorem ipsum</div>

使用此CSS:

#graphic { background-image: url(image.jpg); width: 200px; height: 100px;}

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

background-clip似乎不是正确的CSS属性。我该怎么用呢?

background-position
不应使用,因为我在Sprite上下文中使用了上述CSS,在该Sprite上下文中,我要显示的图像部分小于定义CSS的元素。

关注者
0
被浏览
143
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    您可以将图形放置在具有其自身尺寸上下文的伪元素中:

    #graphic {
      position: relative;
      width: 200px;
      height: 100px;
    }
    #graphic::before {
      position: absolute;
      content: '';
      z-index: -1;
      width: 200px;
      height: 50px;
      background-image: url(image.jpg);
    }
    
    
    
    #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. */
    
    }
    
    
    <div id="graphic">lorem ipsum</div>
    

    浏览器支持很好,但是如果需要支持IE8,请使用单个冒号:beforeIE在此之前的版本中均不支持这两种语法。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看