Is it possible to crop an image using css and display it as a css background?

I would like to know how to display part of the image as a css background.

For example: if the image was 500x500 pixels in size, how would I display the image displaying only the upper left corner of the image (50x50, starting at 0.0)?

+4
source share
5 answers

You can use the CSS property clip. If you want to show only the upper left corner squared 50px x 50px, you can do

position: absolute;
clip: rect(0px, 50px, 50px, 0px);

on the background image. As noted, this is deprecated in the comments, but there are other options.

You can use the CSS property clip-path.

-webkit-clip-path: polygon(0 0, 10% 0, 10% 10%, 0 10%);
-moz-clip-path: polygon(0 0, 10% 0, 10% 10%, 0 10%);
-o-clip-path: polygon(0 0, 10% 0, 10% 10%, 0 10%);
clip-path: polygon(0 0, 10% 0, 10% 10%, 0 10%);

10% , , 50px ,

-webkit-clip-path: inset(0 450px 450px 0);
-moz-clip-path: inset(0 450px 450px 0);
-o-clip-path: inset(0 450px 450px 0);
clip-path: inset(0 450px 450px 0);

div crop

<div class="crop>
    <img src=""/>
</div>

.

.crop {
    width: 50px;
    height: 50px;   
    overflow: hidden;
}

, .crop img.

+1

CSS :

background-position: -50px -50px;

, .

Edit:

,

background-position: ;

:

: 50% 50%;

CSS jsfiddle

.box {
    width: 200px;
    height: 200px; 
    background-image:     url('http://www.sunderlandecho.com/webimage/1.7367190.1437392150!/image/2890796431.jpg_gen/derivatives/landscape_620/2890796431.jpg');
    background-repeat: no-repeat;
   background-position: 50% 50%;
}    

jsfiddle

0

background-size: 50px 50px; background-position: left top;

0

https://jsfiddle.net/iaezzy/msc3az41/1/

-webkit-clip-path: inset(0 450px 450px 0);
-moz-clip-path: inset(0 450px 450px 0);
-o-clip-path: inset(0 450px 450px 0);
clip-path: inset(0 450px 450px 0);
/* values are from-top, from-right, from-bottom, from-left */

http://caniuse.com/#feat=css-clip-path

0

[0,0]

.backImage {
  width: 500px;
  height: 500px;
  background-size: 500px 500px;
  background-image: url('http://i.imgur.com/FNK9ojm.png');
  background-repeat: no-repeat;
  background-position: left top;
 }
.crop {
  width: 50px;
  height: 50px;
}
<div class="backImage crop"></div>
<hr>
<div class="backImage"></div>
Hide result

:

.backImage {
  width: 500px;
  height: 500px;
  background-size: 500px 500px;
  background-image: url('http://i.imgur.com/FNK9ojm.png');
  background-repeat: no-repeat;
  background-position: center center;
 }
.crop {
  width: 50px;
  height: 50px;
}
<div class="backImage crop"></div>
<hr>
<div class="backImage"></div>
Hide result
0

Source: https://habr.com/ru/post/1598792/


All Articles