Clip / Crop background-image with CSS
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 that I apply is 200x100 pixels, but I only want to display the cropped portion of the background image of 200x50 pixels.
background-clip is not a valid CSS property for this. What can i use instead?
background-position should not be used because I use the above CSS in the sprite context, where the part of the image I want to show is smaller than the element on which CSS is defined.
You can put graphics in a pseudo-element with your own spatial context:
#graphic { width: 200px; height: 100px; position: relative; } #graphic::before { content: ''; position: absolute; 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> Browser support is good, but if you need to support IE8, use one colon :before . IE does not support any syntax in versions prior to this.
Perhaps you can write like this:
#graphic { background-image: url(image.jpg); background-position: 0 -50px; width: 200px; height: 100px; } Another option is to use linear-gradient() to hide the edges of your image. Please note that this is a stupid decision, so I am not going to make much effort to explain this ...
.flair { min-width: 50px; /* width larger than sprite */ text-indent: 60px; height: 25px; display: inline-block; background: linear-gradient(#F00, #F00) 50px 0/999px 1px repeat-y, url('https://championmains.imtqy.com/dynamicflairs/riven/spritesheet.png') #F00; } .flair-classic { background-position: 50px 0, 0 -25px; } .flair-r2 { background-position: 50px 0, -50px -175px; } .flair-smite { text-indent: 35px; background-position: 25px 0, -50px -25px; } <img src="https://championmains.imtqy.com/dynamicflairs/riven/spritesheet.png" alt="spritesheet" /><br /> <br /> <span class="flair flair-classic">classic sprite</span><br /><br /> <span class="flair flair-r2">r2 sprite</span><br /><br /> <span class="flair flair-smite">smite sprite</span><br /><br /> I use this method on this page: https://championmains.imtqy.com/dynamicflairs/riven/ and cannot use the ::before or ::after elements because I'm already using them for another hack.