Как обрезать изображение в css
Перейти к содержимому

Как обрезать изображение в css

  • автор:

First Method, Cropping Height

Let’s say we have image with ratio size of 1:1 and we want to change it to ratio size of 16:9.

Calculate Cropping Size

First calculate how much size you need to crop from the picture:

9/16= 56.25(%) /*image percent size after cropping*/

100–56.25 =43.75(%) /*cropping percent value */

44 / 2 = 21.875(%) /*each side*/

Base HTML & CSS

HTML

CSS

Add Cropping Styles

Now just add negative margin to the image

Second Method, Add Height

Now Let’s go the opposite way. Let’s say we have image with ratio size of 16:9 and we want to change it to ratio size of 1:1.

Calculate Additional Size

  • 16/9 = 1.7777 /*missing ratio size for ratio 1:1*/
  • 1.777 * 100 = 177.77(%) /*size for the image before cropping*/
  • 177.77–100 = 77.77 /*additional size that will be cropped*/
  • 77.77/2 = 38.885(%) /*additional size that will be cropped each size*/

Base HTML & CSS

HTML

CSS

Add Cropping Styles

That’s all, I hope you enjoy it.

You Can find me in my facebook groups:
CSS Masters
CSS Masters Israel

Как с помощью CSS сделать обрезку картинки до определенного размера?

nyakiss

Этот класс растянет картинку на всю ширину блока, и автоматически построит ее высоту.

ну и похожий класс описать для варианта 100% hegit и width:auto;

1. Вы используете бутстрап, там этот код уже есть (написанный в этом примере), удалите его из своих стилей, в Ашем случае достаточно просто к картинке добавить img-responsive.
2. Если надо ограничить по высоте, то можно сделать например так:

How to automatically crop and center an image

Given any arbitrary image, I want to crop a square from the center of the image and display it within a given square.

This question is similar to this: CSS Display an Image Resized and Cropped, but I don’t know the size of the image so I can’t use set margins.

9 Answers 9

One solution is to use a background image centered within an element sized to the cropped dimensions.

Basic example

Example with img tag

This version retains the img tag so that we do not lose the ability to drag or right-click to save the image. Credit to Parker Bennett for the opacity trick.

object-fit / -position

The CSS3 Images specification defines the object-fit and object-position properties which together allow for greater control over the scale and position of the image content of an img element. With these, it will be possible to achieve the desired effect:

I was looking for a pure CSS solution using img tags (not the background image way).

I found this brilliant way to achieve the goal on crop thumbnails with css:

It is similar to @Nathan Redblur’s answer but it allows for portrait images, too.

Works like a charm for me. The only thing you need to know about the image is whether it is portrait or landscape in order to set the .portrait class so I had to use a bit of Javascript for this part.

How To Scale and Crop Images with CSS object-fit

How To Scale and Crop Images with CSS object-fit

You will likely encounter a scenario where you will want to preserve the original aspect ratio when working with images. Preserving the aspect ratio will prevent images from appearing distorted by either being stretched or squished. A common solution for this problem is to use the background-image CSS property. A more modern approach would be to use the object-fit CSS property.

In this article, you will explore the effects of the fill , cover , contain , none , and scale-down values available to the object-fit CSS property and how it can crop and scale images. You will also explore the object-position CSS property and how it can offset images.

Prerequisites

If you would like to follow along with this article, you will need:

  • Understanding CSS property and values.
  • Using CSS declarations inline with the style property.
  • A code editor.
  • A modern web browser that supports object-fit and object-position .

Observing the Default Behavior of a Sample Image

Consider the following code used to display a sample image:

This code will produce the following result in the browser:

Sample image of a turtle riding on top of an alligator that is swimming in the water - scaled to 600 x 337.

This image has an original width of 1200px and a height of 674px. Using img attributes, the width has been set to 600 and 337 — half the original dimensions — preserving the aspect ratio.

Now, consider a situation where the layout expects images to occupy a width of 300px and a height of 337px:

This code will produce the following result in the browser:

Sample image of a tutle riding on top of an alligator that is swimming in the water - scaled to 300 x 337.

The resulting image no longer preserves the original aspect ratio and appears to be visually “squished”.

Using object-fit: fill

The fill value is the initial value for object-fit . This value will not preserve the original aspect ratio.

This code will produce the following result in the browser:

Sample image of a tutle riding on top of an alligator that is swimming in the water - scaled to 300 x 337 - with object-fit: fill.

As this is the “initial” value for browser rendering engines, there is no change in appearance from the scaled image. The resulting image still appears squished.

Using object-fit: cover

The cover value preserves the original aspect ratio, but the image occupies all the available space.

This code will produce the following result in the browser:

Sample image of a tutle riding on top of an alligator that is swimming in the water - scaled to 300 x 337 with object-fit: cover.

In certain situations, object-fit: cover will result in the image appearing cropped. In this example image, some parts of the original image on the left and right do not appear because they cannot fit within the bounds of the declared width.

Using object-fit: contain

The contain value preserves the original aspect ratio, but the image is also constrained to not exceed the bounds of the available space.

This code will produce the following result in the browser:

Sample image of a tutle riding on top of an alligator that is swimming in the water - scaled to 300 x 337 - with object-fit: contain.

In certain situations, object-fit: contain will result in the image not filling all the available space. In this example image, there is vertical space above and below the image because the declared height is taller than the scaled-down height.

Using object-fit: none

The none value does not resize the image at all.

This code will produce the following result in the browser:

Sample image of a tutle riding on top of an alligator that is swimming in the water - scaled to 300 x 337 - with object-fit: none.

In situations where the image is larger than the available space, it will appear cropped. In this example image, some parts of the original image on the left, right, top, and bottom do not appear because they cannot fit within the bounds of the declared width and height.

Using object-fit: scale-down

The scale-down value will either display an image like contain or none depending on which would result in a smaller image.

This code will produce the following result in the browser:

Sample image of a tutle riding on top of an alligator that is swimming in the water - scaled to 300 x 337 - with object-fit: scale-down.

In this example image, the image has been scaled down to behave like contain .

Using object-fit and object-position

If the resulting image from object-fit appears cropped, by default the image will appear centered. The object-position property can be used to change the point of focus.

Consider the object-fit: cover example from before:

Sample image of a tutle riding on top of an alligator that is swimming in the water - scaled to 300 x 337 with object-fit: cover.

Now let’s change the position of the visible part of the image on the X-axis to reveal the right-most edge of the image:

This code will produce the following result in the browser:

Sample image cropped to display an alligator that is swimming in the water - scaled to 300 x 337 - with object-fit: contain and object-position: 100% 0.

In this example image, the turtle has been cropped out of the image.

And finally, let’s observe what happens if the position is specified outside of the bounds of the available space:

This code will produce the following result in the browser:

Sample image cropped to display part of a turle and part of an alligator that is swimming in the water - scaled to 300 x 337 - with object-fit: contain and object-position: -20% 0.

In this example image, the turtle and alligator heads have been cropped out of the image. There is also spacing to make up the 20% of offset on the left of the image.

Conclusion

In this article, you explored the values available for the object-fit and object-position CSS properties.

Before using object-fit in your project, verify that it is supported in the browsers used by your intended audience by checking the browser support on Can I Use?.

If you’d like to learn more about CSS, check out our CSS topic page for exercises and programming projects.

Want to deploy your application quickly? Try Cloudways, the #1 managed hosting provider for small-to-medium businesses, agencies, and developers — for free. DigitalOcean and Cloudways together will give you a reliable, scalable, and hassle-free managed hosting experience with anytime support that makes all your hosting worries a thing of the past. Start with $100 in free credits!

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *