开发者

Crop an image instead of stretching it

When I insert an image in a container with fixed width and height, the image stretches to fit that space. Is there a way to display the image at its normal size, but with开发者_运维技巧 the excess clipped out?


The modern way is to use object-fit: none; (or the more common object-fit: cover; if you want to scale, but without stretching).

img {
    object-fit: cover;
}

97% of browser sessions support this as of 2022 May. — Can I use?


If you want to anchor the image to the top left corner instead of the center, add:

img {
    object-position: 0 0;
}


<div style="width: 100px; height: 100px; background-image: url(your image); background-repeat: no-repeat;"></div>

Then in the above DIV you can play with CSS

  • width/height
  • background-position

to create different crop effects.


You can use the CSS clip property:

#image_element
{
position:absolute;
clip:rect(0px,60px,200px,0px);
}

The downside of using clip is that the element has to be absolutely positioned, and is only available with the 'rect' shape.

See:

  • https://www.w3schools.com/cssref/pr_pos_clip.asp
  • http://www.cssplay.co.uk/menu/clip_gallery


Use this : http://www.w3schools.com/css/pr_background-position.asp

background-position: 5px 5px;

and then set the height and width of the div

height: 55px;

width: 55px;


Show it as a background image

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜