Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have this HTML:

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

with this CSS:

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

The background image I'm applying is 200x100 px, but I only want to display a cropped portion of the background image of 200x50 px.

background-clip does not appear to be the right CSS property for this. What can I use instead?

background-position should not be used, because I'm using the above CSS in a sprite context where the image part I want to show is smaller than the element on which the CSS is defined.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
501 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can put the graphic in a pseudo-element with its own dimensional context:

#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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...