MEDIA GUIDES / Automatic Image Cropping

5 Ways to Crop Images in HTML/CSS

crop images html css

Key takeaways:

  • There is no HTML crop attribute. Cropping is a CSS job, a server or CDN job, or a JavaScript canvas job.
  • object-fit: cover with object-position handles most fixed-size image slots in four declarations.
  • aspect-ratio holds a shape rather than a size, which is what responsive cards and grids need.
  • border-radius and clip-path crop to shapes. A wrapper with overflow: hidden crops without scaling the image at all.
  • No CSS method reduces the bytes the browser downloads. Only cropping the file does that.
  • CSS cannot find a face or a subject. Content-aware cropping happens where the pixels are processed.

Cropping is the process of removing certain regions of an image and reducing image size accordingly. It can be used to focus on specific elements in an image, remove extraneous details, or reframe the subject to attract attention to a specific part of an image.

You can crop images using plain HTML5 and CSS code, without using JavaScript or any other scripting language. We’ll show several techniques for achieving this, most of which take advantage of CSS properties like width, height, overflow, object-fit, object-position, and padding-top. Another option is to use Cloudinary to automatically crop images with smart detection of relevant objects in the image.

In this article:

How Do You Crop an Image in HTML?

HTML has no crop attribute. You crop in CSS: give the image a fixed box, then set object-fit: cover so the image fills that box and whatever falls outside it is clipped. Add object-position to choose which part of the image survives the crop. This changes what the browser draws, not what it downloads, so the full original file still crosses the network.

<img src="dogs.jpg" alt="Two dogs running on a beach" class="crop">

CSS:

.crop {

 width: 400px;

 height: 400px;

 object-fit: cover;

 object-position: 50% 30%;

}

The methods below cover the narrower cases: a crop that does not scale the image at all, a box that holds a shape rather than a size, a circle, an arbitrary polygon, a zoom. If what matters is the size of the download rather than the framing, crop the file instead of the display, which is covered further down.

What Are the Benefits of Cropping an Image?

Concentrate On A Subject

Cropping an image enables you to zoom in or out on a subject. You can use this technique to engage a subject and increase the photo’s magnification. As a result, you shift the focus to the subject.

Remove Too Much Visual Information

Too much visual information can create a distracting effect. Instead of attracting the subject’s attention, it distracts, and as a result, the viewer ignores the image. Cropping images can help you shift the focus to the main topic, remove unnecessary information and inappropriate positions, and prevent random objects from interfering with the frame.

Cropping for Composition

You can use image cropping techniques for image composition. For example, you can split the image into 3×3 grids, align elements on the grid lines, and crop according to the Rule of Thirds. In portraits, you can match the eyes to the grid lines, and in other images, you can shift the focus to the main theme.

Unusual Shapes

Ideally, users should view a web page while following messages and call to action (CTAs) prompts. They should not stop to analyze the design. Unusual shapes, like diamonds and stars, can make viewers pause to consider the reason behind the shape, shifting their focus from the message to the design. You can crop these shapes into a circle or any shape that keeps your audience engaged with the message.

Automatically resize and crop image with AI

Which CSS Cropping Method Should You Use?

Seven CSS methods crop an image. They differ in whether the image is scaled, in whether the box holds a shape or a size, and in which shapes are available.

Method What it does Keeps the aspect ratio Best for
object-fit: cover Scales the image to fill its box and clips the overflow Yes Almost every fixed-size image slot
Container with overflow: hidden Hides whatever extends past a sized wrapper Yes, the image is never scaled A hand-positioned crop on one specific image
aspect-ratio Holds the box at a fixed ratio at any width Yes Responsive cards and grids
background-size: cover Crops the image as a container background Yes Decorative imagery with no semantic role
border-radius Masks the box to a circle or an ellipse Yes, paired with object-fit Avatars and profile pictures
clip-path Clips to a rectangle, circle, ellipse, polygon or SVG path Yes, paired with object-fit Shaped and angled crops
transform: scale() Zooms into the image and shifts the visible region Yes Zoom on hover, fine focal adjustment

Crop Using Width, Height, and Overflow CSS Properties

In addition to the well-known width and height properties, CSS containers have an overflow property you can use to crop images.

To enable the overflow property, wrap the image in a <div> element with a specified width and height, and set overflow to hidden.

HTML:

<div class="wrap">
    <img src="dogs.jpg" class="myImage">
</div>

CSS:
.wrap {
    width: 400px;
    height: 400px;
    overflow: hidden;
}


Example:

The next image has 640px width and 480px height, and we will wrap it in a 400px x 400px container:

Original Image:

css crop image

Cropped Image:

css crop image

This ensures:

  1. The container keeps its structure,
  2. The overflow of images included in the container will be hidden behind it.

Define the Crop Region

As you can see, now the dogs are out of focus.

We can fix it by taking advantage of the CSS margin property.

The margin property has four values: top, right, bottom, and left.

But instead of setting the values on positives, we will use the negative values to move the image to center the dogs.

In this case, we need to move the image to the left, and a little bit to the top.

.myImage {
    margin: -40px 0px 0px -120px;
}

css crop image

Now the dogs looks pretty good!

Crop Using object-fit and object-position

The object-fit CSS property is also useful for cropping images. It has 5 possible values—the cover value is the most useful for cropping. This maintains the aspect ratio of the image, ensuring it fits the dimensions of the content box.

You can use the object-fit property in conjunction with object-position to adjust the area of the image to crop. The object-position property requires two values: x% and y% to position the image (the default position is 50% 50%).

The code below uses the class cropped-ofp to crop an original image of 300px by 300px to half its original size, and positions it in the bottom left quadrant with object-position equal to 25% 25%.

<html>
<head>
<style>
.cropped-ofp {

width: 150px; 

height: 150px; 

object-fit: cover;

object-position: 25% 25%; 

}
</style>
</head>
<body>
<img src="https://example.com/myimage.png" alt="Product photograph of a leather handbag" class="cropped-ofp">
</body>
</html>

Other object-fit values

For your reference, here are other options you can use for object-fit, which can also be used to crop images:

  • contain: Scales the image to fit the container while maintaining its aspect ratio. Typically the image will not fill the container, unless its aspect ratio is identical to the container’s.
  • fill: Resizes the image to fit the container. If the aspect ratio of the image is different from that of the container, the image is stretched or squeezed to fit.
  • none: Displays the image in the container without resizing it.
  • scale-down: Sizes the content as if none or contain were specified, whichever produces the smaller result. Like every other value, it changes only how the image is drawn, not the size of the file downloaded.

Aspect Ratio Cropping with calc() and padding-top

This technique lets you crop an image to a desired aspect ratio. It requires a few steps:

  • Define an image with height set to 0 and padding-top set to a percentage of the container’s width. Set position to relative.
.image-box {
    position: relative;
    width: 100%;
    height: 0;
    padding-top: calc(100% * (100 / 300));
}
  • Now set the image width and height to 100%, and define image position as absolute with a top value of 0.
.image-cropped-calc {
    position: absolute;
    top: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
}
  • You can now specify any aspect ratio to crop the image, by setting the padding-top value of the container using the calc() function.

The percentage works because a percentage padding-top resolves against the width of the container, not its height, so a percentage of the width becomes the height.

Crop to an Aspect Ratio with the aspect-ratio Property

The padding technique above predates a property built for the job. aspect-ratio sets the shape of the box directly, with no wrapper, no height: 0 and no absolute positioning.

.card-image {

 width: 100%;

 aspect-ratio: 16 / 9;

 object-fit: cover;

}

Three declarations give a full-width image that holds a 16:9 box at every viewport width, crops to fill it, and never distorts. Change the ratio to 1 / 1 for a square, 4 / 5 for a portrait slot, or 3 / 2 for a classic photographic frame. Because the browser can work out the height of the box from its width before the image arrives, this also reserves the space and stops the layout jumping as images load.

Crop Using CSS Transforms

The CSS transform property lets you perform several image operations on an element, including rotate, scale, skew, and translate (reposition the element in the grid).

You can use the transform property to crop images by combining the scale and translate operations. Here is an example:

.image-cropped-transform {

 position: absolute;

 top: 0;

 width: 100%;

 height: 100%;

 object-fit: cover;

 object-position: 55%;

 transform: scale(0.5) translate(0, 5%);

}

Two details decide whether a transform actually crops. The scale factor has to be above 1, because a factor below 1 shrinks the image inside its box and leaves empty space rather than removing anything. And the wrapper needs overflow: hidden, because transform moves pixels without clipping them, so the enlarged image otherwise spills over its neighbors. A zoom crop looks like this:

<div class="zoom-wrap">

 <img src="dogs.jpg" alt="Two dogs running on a beach" class="zoom-image">

</div>
CSS:

.zoom-wrap {

 width: 400px;

 height: 400px;

 overflow: hidden;

}

.zoom-image {

 width: 100%;

 height: 100%;

 object-fit: cover;

 transform: scale(1.4);

 transform-origin: center;

}

Scale factors above 1 enlarge the source, so push them too far and the crop goes soft. An image delivered at its display size has no spare pixels, and scale(2) on it will look blurry. This method earns its place in interactions, a zoom on hover or on focus, more than in static layout.

Crop with the clip-path() Function

The CSS clip-path() property is especially designed to show only part of an image, which is exactly what we need for cropping. The “clipped” region is displayed, while the rest of the image is hidden.

A nice thing about this property is that it lets you specify the shape and position of the crop. It uses coordinates to define points in a two-dimensional space, which you can use to create and position shapes on the image, and define the crop shape.

CSS clip-path() accepts one of the following functions as its accepted values:

  • inset(): Defines an inset rectangle
  • circle(): Defines a circle
  • ellipse(): Defines an ellipse shape
  • path(): Accepts an SVG path string, which can define an arbitrary shape
  • polygon(): Defines a polygon using multiple points

Here is an example showing how to use inset() to crop the image to a rectangle:

.cropped-image-clip-rectangle {

 height: 100%;

 clip-path: inset(20px 50px 10px 0 round 50px);

}

Here is an example showing how to use polygon() function to crop the image to a triangle shape:

.cropped-image-clip-polygon {

 height: 100%;

 clip-path: polygon(50% 0%, 0% 100%, 100% 100%);

}

Older tutorials crop with the clip property and rect() instead. Do not copy them. MDN marks clip as deprecated, notes that the CSS Masking specification deprecated it, and tells authors to use clip-path.

Crop a Background Image with background-size and background-position

An image set as a container background crops to that container by default, with no wrapper and no overflow rule. background-size: cover scales it to fill the box, and background-position picks the focal point.

<div class="hero" role="img" aria-label="Sunset over a mountain range"></div>
.hero {

 width: 100%;

 aspect-ratio: 21 / 9;

 background-image: url("sunset.jpg");

 background-size: cover;

 background-position: center;

 background-repeat: no-repeat;

}

Swap cover for contain to fit the whole image inside the box instead of cropping it, or give an explicit size such as background-size: 150% to zoom in before positioning.

One caveat decides whether this method is appropriate. A background image is not content, so it takes no alt text and screen readers do not announce it. Keep it for decoration, or, where the image carries meaning, add role=”img” and aria-label as above, or use an img element and crop it with object-fit.

Crop to a Circle or an Ellipse with border-radius

For avatars, crop the box to a circle. border-radius: 50% rounds every corner to half the size of the element, which on a square element is a circle. Pair it with object-fit: cover so a source that is not square is cropped rather than squashed.

.avatar {

 width: 96px;

 height: 96px;

 object-fit: cover;

 border-radius: 50%;

}

Give the element different width and height values and the same border-radius: 50% produces an ellipse, or cut the shape into the file itself with the ellipse crop tool. This is the cheapest of the shaped crops: one property, and no extra markup.

Does CSS Cropping Reduce Image File Size?

No. None of these methods changes the file the browser downloads. A width and height of 150 pixels with object-fit: cover renders a 150 pixel thumbnail from whatever you pointed src at, and if that is a 5 MB camera original then every visitor downloads 5 MB to look at a thumbnail. The crop costs decode time and memory too, because the browser decodes the full image before clipping it.

That matters most where cropped images cluster: product grids, galleries, avatar lists, anywhere a page shows dozens of small images. It also bears on Largest Contentful Paint, which measures when the largest image or text block in the viewport finishes rendering, so an oversized file sitting in a hero slot delays that measurement directly.

CSS cropping is the right tool when the layout decides the crop and the source is already close to the delivered size. Crop the file instead when the source is far larger than the slot, when the same crop goes to everyone, or when the right region depends on what is in the picture rather than on where the box is.

Crop the File Instead: How Image CDNs Compare

Image CDNs crop by URL. You keep one master file, and the dimensions, crop mode and focal point travel as parameters, so the browser receives an already cropped image at the size it will display. Several services work this way, with different syntax. The table below records how each one asks for a crop and what each one’s own documentation names for automatic subject detection.

Service How you ask for a crop Automatic subject detection named in its documentation
Cloudinary Path parameters, for example c_fill,g_auto,w_300,h_169 g_auto for an automatically determined area of interest, g_face for the single largest face, g_faces for all detected faces
imgix Query parameters, for example ?fit=crop&w=300&h=100 fit=smart-crop, documented as shorthand for fit=crop&crop=auto, and fit=facearea with faceindex and facepad
ImageKit Path parameters, for example c-maintain_ratio, cm-extract, cm-pad_resize, c-force, c-at_max, c-at_least fo-auto, fo-face, and fo- followed by an object name
Uploadcare Path modifiers, for example -/crop/ and -/scale_crop/ A smart modifier for face and object detection
Thumbor Path segments: AxB:CxD for the left-top and right-bottom crop coordinates, ExF for the output size A smart segment for focal point detection, off by default

The syntax differs but the principle does not. The crop is expressed in the URL, so one stored file serves every variant and the browser is never sent pixels it will not display. Thumbor is the one in this group that you run on your own infrastructure rather than buy as a hosted service.

Fully Automated Image Resize and Cropping with Cloudinary

A cloud-based service for managing images and videos, Cloudinary offers a generous free-forever subscription plan. While on that platform, you can upload your images, apply built-in effects, filters, and modifications. You can also resize images automatically, focusing on the most important elements with AI or adapt them to your website design without having to manually crop or scale them.

You can set the target dimensions of your resized image by specifying width, height, and/or the target aspect ratio as qualifiers of your resize transformation.

You can change the dimensions of an uploaded image by setting the image’s height, width, and/or aspect ratio, and Cloudinary automatically resizes or crops the image to fit into the requested size.

For example, this original image is 1200 x 1200 pixels:

Resizing the image to 200 x 200 pixels, using crop, scale, fill and pad results in the following images:

Cloudinary Crop Modes

The transformation goes in the URL path, between the delivery type and the public ID. Each parameter is an abbreviation: w for width, h for height, ar for aspect ratio, c for the crop mode and g for gravity. These six modes crop, which is to say they discard part of the image when the requested aspect ratio differs from the original.

Mode URL parameter What it does
fill c_fill Resizes the image to fill the specified dimensions without distortion. The image may be cropped as a result.
lfill c_lfill Same as fill, but only scales down the image.
fill_pad c_fill_pad Same as fill, but avoids excessive cropping by adding padding when needed.
crop c_crop Extracts a region of the specified dimensions from the original image without first resizing it.
thumb c_thumb Creates a thumbnail of the image with the specified dimensions, based on a specified gravity.
auto c_auto Automatically determines the best crop based on a specified gravity. Scaling may occur.

The resize and padding modes do not discard content: c_scale resizes without necessarily keeping the original aspect ratio, c_fit and its scale-down and scale-up variants fit the image inside a bounding box, and c_pad, c_lpad and c_mpad pad the result to fill the requested area. Full definitions are in the resizing and cropping documentation.

Automatic gravity is a heuristic rather than a guarantee. g_auto keeps the region it scores as most interesting, which is usually the right one and sometimes is not, so check it across your own library before trusting it for art direction.

Keeping Crop URLs Under Your Control

A URL-based crop API has one consequence worth settling before you adopt one: the numbers in your image URLs are editable by anyone who can read them, so a visitor can change w_300 to w_4000 and request variants you never intended. Cloudinary answers this with three controls, all set out in the control access to media documentation.

  • Strict transformations block on-the-fly transformations unless they are explicitly allowed. With them enabled, transformations can only be created through eager transformations, signed delivery URLs, allowed named transformations or allowed referral domains, and applying a transformation that is not allowed returns a 404.
  • Signed delivery URLs carry a signature that covers both the public ID and any transformations in the URL, so an edited URL fails. The documentation is explicit that signing does not prevent link sharing: it stops URL tampering, not forwarding.
  • Token-based authentication appends a signed token that restricts access by time, IP or URL pattern. Expiry belongs to this control rather than to signing: you supply either a duration in seconds or an expiration as a UNIX timestamp, and if both are given the duration is ignored.

Transformation access control is the trust question this subject raises. It decides who can mint a new crop of your media, which is a different question from how the stored bytes are protected.

Pro Tip!

Simplify image transformations through URLs

Resize, crop, and enhance images instantly with simple URL tweaks. Skip the editing tools and move faster.


→ Discover a smarter way to transform images.

Frequently Asked Questions

Can you crop an image in HTML without CSS?

No. HTML has no crop attribute. The width and height attributes on an img element scale the image and reserve space for it, but they do not remove any part of it, and setting them to a ratio other than the source’s distorts it. To crop you need CSS, a server-side or CDN transformation, or JavaScript drawing the image onto a canvas.

Does CSS cropping reduce image file size?

No. Every CSS method changes what the browser displays after the file has been downloaded and decoded, so the bytes over the network are unchanged. To reduce the download you have to crop the file, either before upload or through a URL-based transformation.

How do you crop an image to a circle in CSS?

Give the element equal width and height, add object-fit: cover so a source that is not square is not squashed, and set border-radius: 50%. clip-path: circle(50%) gives the same result and also lets you move the center of the circle.

How do you crop an image to a square in CSS?

Set aspect-ratio: 1 / 1 with object-fit: cover and let the width come from the layout. The box stays square at any width and the image fills it without distortion.

What is the difference between object-fit: cover and object-fit: contain?

Per MDN, cover sizes the image to fill the entire content box and clips it if the aspect ratios do not match, so you always get a full box and sometimes lose part of the image. contain scales the image to fit inside the content box, so it is letterboxed or pillarboxed instead of clipped. cover crops, contain does not.

Is clip-path or overflow: hidden better for cropping?

A sized wrapper with overflow: hidden is the simpler choice for rectangular crops. clip-path is the better choice when you need a shape that is not a rectangle, or when you want to place the clipped region with coordinates. For a plain rectangle, object-fit: cover is usually less code than either.

Can CSS crop around a face automatically?

No. CSS has no knowledge of what is in an image, so it can only position a box by numbers you supply. Content-aware cropping happens where the pixels are processed: a CDN or server transformation, such as g_face or g_auto in a Cloudinary delivery URL, or JavaScript running a detection model in the browser.

QUICK TIPS
Jen Looper
Cloudinary Logo Jen Looper

In my experience, here are tips that can help you better implement and optimize image cropping using HTML and CSS:

  1. Use the object-fit property for responsive image containers
    When dealing with responsive image containers, always prefer object-fit: cover for simple, centered crops without cutting off crucial content. This method scales and centers the image within its container, ensuring the most visually appealing portion remains visible across different screen sizes.
  2. Center images using negative margins
    If you’re using overflow: hidden to crop an image, negative margins are an excellent way to reposition and center the image. Experiment with values for margin-top and margin-left to ensure that the focus area remains prominent. This works well for fine-tuning specific elements within the image, such as centering a face or a product.
  3. Combine clip-path for custom shapes
    The clip-path property is highly versatile and allows for creative cropping beyond standard squares and rectangles. Use polygon() for creating custom shapes like triangles or diamonds, and circle() or ellipse() for circular cropping. This method can be useful for profile pictures, iconography, or highlighting sections of a complex image layout.
  4. Use clip-path with SVG paths for precision cropping
    When you need precise control over cropping areas (e.g., cropping around irregular shapes), leverage clip-path with the path() function to create SVG paths. This allows you to define intricate cropping patterns, such as complex logos or product outlines, directly with CSS.
  5. Use calc() for maintaining aspect ratios dynamically
    The padding-top technique combined with calc() is ideal for maintaining consistent aspect ratios in responsive designs. This approach adapts the container’s height proportionally based on its width, preserving the intended aspect ratio regardless of the screen size. This is especially useful for images in grid layouts, ensuring visual consistency across different breakpoints.
  6. Combine transform and object-position for advanced image positioning
    Use transform properties like translate and scale in combination with object-position to precisely crop and position images within their containers. This technique is particularly effective for fine-tuning background images or image galleries, where you need to highlight specific sections without resizing the original image.
  7. Set up fallback styles for unsupported browsers
    Not all CSS cropping methods are supported in every browser. When using modern techniques like clip-path or object-fit, always set up fallback styles (e.g., using overflow: hidden or background-position) to ensure a consistent appearance in older browsers. This prevents visual disruptions and keeps your design accessible.
  8. Minimize file sizes with pre-cropped server-side images
    Although CSS cropping methods are convenient, they don’t reduce file size. Whenever possible, use server-side tools (e.g., Cloudinary) to crop and resize images before delivering them to the browser. This approach cuts down on bandwidth usage and improves page load times, making it essential for performance-optimized websites.
  9. Use Cloudinary’s g_auto (gravity auto) for smart cropping
    For complex images where CSS-based cropping might obscure important content, Cloudinary’s g_auto (gravity auto) can dynamically detect and focus on the most relevant parts of an image, like faces or products. This method is excellent for generating responsive thumbnails or hero images that adapt to different screen sizes.
  10. Optimize image delivery with responsive breakpoints
    Leverage responsive breakpoints with tools like Cloudinary to deliver different image sizes based on the viewport dimensions. This ensures that each device gets a tailored image version without wasting resources, enhancing performance and visual fidelity.

By integrating these tips, you can achieve more polished and responsive image layouts using HTML and CSS, while maintaining optimal performance and user experience across devices.

Last updated: Nov 4, 2026
★★★★★
4.8 (22 reviews)
Talk to Sales Talk to Sales