Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 735
Dahie Avatar asked Oct 15 '11 10:10

Dahie


People also ask

How do you crop a background image in CSS?

You can use object-fit along with object-position to crop an image in CSS. Try setting the object-fit property on an image to none and then set object-position: 50% 50% . This will center the image in the container.

Can you crop an image in CSS?

The object-fit CSS property can be used to easily crop images. It can have five values, but cover is the most suitable. By setting object-fit: cover; , the aspect ratio of the image is preserved while still fitting into the size of its content box.

How can I display just a portion of an image in HTML CSS?

One way to do it is to set the image you want to display as a background in a container (td, div, span etc) and then adjust background-position to get the sprite you want. Just to clarify, you'd set the width and height of the container td, div, span or whatever to 50px to make this work.


2 Answers

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>

Browser support is good, but if you need to support IE8, use a single colon :before. IE has no support for either syntax in versions prior to that.

like image 117
Brent Avatar answered Oct 08 '22 20:10

Brent


may be you can write like this:

#graphic {   background-image: url(image.jpg);   background-position: 0 -50px;   width: 200px;   height: 100px; } 
like image 44
sandeep Avatar answered Oct 08 '22 20:10

sandeep