Sub topic 10
Cropping in the browser with CSS
This chapter assumes you know basic HTML (the img element and its attributes), basic CSS (selectors, width and height), and how breakpoints work in a responsive layout. It also assumes you have already chosen an aspect ratio and located the focal point of your photo. Here you apply those decisions in the browser, without editing the file.
Why crop in CSS at all
A photo file has one fixed shape, such as 3:2. A layout often needs a different shape: a 16:9 hero, a square card thumbnail, a tall sidebar portrait. If you force the img element to those dimensions without any other instruction, the browser stretches the photo to fit, and faces look wrong.
CSS lets you keep the original file and tell the browser how to fit it into a box. Three properties do most of the work:
aspect-ratiodefines the shape of the box.object-fitdecides how the image fills the box.object-positiondecides which part of the image stays visible when some of it is cut off.
Editing the file is still better when you need a very different crop for small screens. That case is covered in the next chapter. CSS cropping is for adjusting one photo to the shapes your layout needs.
Setting the box with aspect-ratio
The aspect-ratio property sets the width-to-height ratio of an element. You write it as two numbers separated by a slash.
.card img {
width: 100%;
aspect-ratio: 1 / 1;
}The width comes from the layout, and the browser works out the height from the ratio. If the card is 300px wide, the image box is 300px tall. When the container resizes, the box keeps its shape.
If you set both width and height explicitly, aspect-ratio has no effect, because both dimensions are already fixed. Set one dimension and let the ratio supply the other.
Choosing a fit with object-fit
Once the box and the photo have different shapes, object-fit controls what happens. It applies to replaced elements such as img and video.
| Value | Behavior | Typical result |
|---|---|---|
| `fill` (default) | Stretches the image to the box | Distorted proportions |
| `contain` | Scales the whole image to fit inside the box | Empty bands on two sides (letterboxing) |
| `cover` | Scales the image until it fills the box, then cuts the overflow | No empty space, some edges lost |
| `none` | Keeps the original size | Large images are cut off, small ones leave gaps |
| `scale-down` | Uses `none` or `contain`, whichever is smaller | Never enlarges the image |
For photos, cover is the usual choice because it fills the box without distortion. contain suits cases where nothing may be cut, such as a product photo or a logo, and you accept empty space around it.
The cost of cover is that cropping happens automatically, and the browser does not know where your subject is. By default it keeps the center and discards equal amounts from both sides.
Steering the crop with object-position
object-position moves the image inside its box. Its default is 50% 50%, which is the center. The two values are horizontal and vertical positions.
The idea is that a percentage aligns the same percentage point of the image with the same point of the box. At 0% the left edge of the image lines up with the left edge of the box. At 100% the right edges line up. This is why it works as a "move the visible window" control.
The example from this tutorial's plan puts it together:
.hero img {
width: 100%;
aspect-ratio: 16 / 9;
object-fit: cover;
object-position: 30% 40%;
}The image fills a 16:9 box, the browser crops the overflow, and object-position moves the visible area toward the subject instead of the center.
Position only matters along the axis where something is cropped. Suppose a 3:2 photo goes into a 16:9 box with cover. The photo is relatively taller than the box, so the browser trims the top and bottom. The horizontal value in object-position then has no visible effect, and the vertical value decides how much comes off the top versus the bottom.
Turning a focal point into numbers
In the previous chapter you located the focal point. To convert it, estimate where the subject sits as a percentage of the photo's width and height. A subject whose face is about a third of the way from the left and 25% from the top gives object-position: 33% 25%.
Because the percentage rule aligns matching points, a focal point value is only an approximation of what you see. After setting it, check the result in the browser rather than trusting the math. Adjust in steps of 5 to 10 percent until the subject has comfortable room.
You can also use keywords: top, bottom, left, right, and center. For example, object-position: center top keeps the top of a portrait, which protects faces in a tall photo cropped to a wide box.
A worked example: one photo, three shapes
Suppose one photo of a baker at an oven is used as a hero banner, a card thumbnail, and a profile tile. The subject sits in the left part of the frame.
<section class="hero">
<img class="shot shot--wide" src="baker.jpg" width="1600" height="1067"
alt="A baker lifting a loaf from a stone oven">
</section>
<ul class="cards">
<li><img class="shot shot--card" src="baker.jpg" width="1600" height="1067"
alt="A baker lifting a loaf from a stone oven"></li>
</ul>.shot {
display: block;
width: 100%;
height: auto;
object-fit: cover;
object-position: 30% 35%;
}
.shot--wide {
aspect-ratio: 21 / 9;
}
.shot--card {
aspect-ratio: 4 / 3;
}
@media (max-width: 600px) {
.shot--wide {
aspect-ratio: 4 / 3;
}
}All variants share one focal point, set once in .shot. Only the ratio changes. On narrow screens the hero switches from 21:9 to 4:3, so the subject is not squeezed into a thin strip.
Note that height: auto combined with aspect-ratio lets the ratio control height. Without height: auto, the height attribute in the HTML can set a fixed height and the ratio would be ignored.
Cropping inside a fixed-height container
Sometimes the layout fixes the height, such as a banner that is always 320px tall. In that case, set the dimensions on the image directly.
.banner img {
display: block;
width: 100%;
height: 320px;
object-fit: cover;
object-position: center 20%;
}The width follows the container, the height is fixed, and the visible crop changes as the container width changes. On a very wide screen, the box is much wider than it is tall, so most of the photo's height is cut away. Check the widest and narrowest layouts, because a fixed height gives you less control over the resulting ratio than aspect-ratio does.
Common errors
- Setting
object-fiton the wrong element. It must be on theimgitself. If you put it on a wrapperdiv, nothing changes. - Forgetting that
covercuts content. A photo with text in it, such as a sign, can lose the text. Usecontainor a separate crop. - Overriding the ratio with a fixed height. An explicit
heightvalue beatsaspect-ratio. Useheight: auto. - Tuning the position on only one screen size. The visible area changes at every width, so test several.
- Relying on CSS for extreme crops. If the box shows less than about a third of the photo, the browser still downloads the full file. A tighter, separately exported crop saves bytes and gives better control.
- Removing the
widthandheightattributes. These let the browser reserve space before the file loads. Keep them, and let CSS control the displayed size. The chapter on layout shift covers this.
Background images as an alternative
You can crop a CSS background image with background-size: cover and background-position. These work like object-fit and object-position. Use img for content photos, because only img carries alt text and works with srcset. Use backgrounds for purely decorative imagery.
.decor {
background-image: url("texture.jpg");
background-size: cover;
background-position: 30% 40%;
}Summary of the decision
- Decide the box shape with
aspect-ratio, or a fixed height if the layout demands it. - Use
object-fit: coverto fill the box without distortion, orcontainwhen nothing may be cut. - Use
object-positionto move the visible window onto the focal point. - Change the ratio at breakpoints, and check the result at several widths.
Exercise
A 3:2 landscape photo of a person standing near the top-left corner is placed in a square box with width: 100%; aspect-ratio: 1 / 1; object-fit: cover;. The person's head is cut off. Which axis does the crop happen on, and which object-position value would you try first?
Show answer
The photo is wider than the square, so the browser trims the left and right sides. The horizontal position decides what stays. Because the person is toward the left, try object-position: 15% 50% (or left center) so the left part remains visible. The vertical value has little effect, because nothing is cropped vertically. If the head is still cut off at the top, the problem is in the source image, since the box is already showing the full height of the photo.
Exercise
A teammate wrote .hero { aspect-ratio: 16 / 9; object-fit: cover; } on a div that wraps the hero img, and the photo still looks stretched. What are two things to fix?
Show answer
First, move object-fit: cover onto the img element, because it only applies to replaced elements. Second, make the img fill the wrapper (width: 100%; height: 100%) or put aspect-ratio on the img with height: auto. Then the image has a box with a defined shape to fill.