How to crop an image in HTML
In this article we will learn how to crop an image in HTML, that is, it will fill our container perfectly without distortion.

What’s up programmer, ok? Do you want to learn something new?
We often need to insert images in <divs>, and the images are not always correctly positioned
And they can even distort, as they are not the same size
So with some CSS in our HTML, we can solve this problem
The central idea is to add the image to the background of a <div> by CSS
And this way, it will never be distorted, as the image is the background and not limited to the width and height of the div
Let’s see in practice, here’s the HTML:
<!DOCTYPE html> <html> <head> <title>Como recortar uma imagem no HTML</title> <meta charset="utf-8"> </head> <body> <div id="container"></div> </body> </html>
Now let’s go to the CSS, which will insert the image at the bottom of the div:
#container { width: 1200px; height: 400px; background-image: url('./bg-img.jpg'); }
We will have this result:
See that the image does not distort the width of the container is respected, we can also reposition this image, see it:
#container { width: 1200px; height: 400px; background-image: url('./bg-img.jpg'); background-position: -100px -450px; }
The result:
Or let it adapt to the space we have:
#container { width: 1200px; height: 400px; background-image: url('./bg-img.jpg'); background-size: cover; }
The result:
The background-size property with a value of cover, makes this image adaptation for us
Also test other values for background-position and background-size
You may find one that better aligns with your project needs.
Conclusion
In this article we learned how to crop an image in HTML, but we actually use CSS for it 😀
Instead of using the img tag, it’s always good to think about the possibility of background-img
that solves these cases where the image distorts, because of the size mismatch of the divs
Want to learn more about HTML and CSS? Click here!