DEV Community

HidetoshiYanagisawa
HidetoshiYanagisawa

Posted on

Master Image Resize Modes in HTML/CSS with object-fit

Hello everyone, today I'm going to explain how to resize images in HTML and CSS. By using the object-fit property, you can freely control images. In this post, I will introduce how to use and remember it.

Table of Contents

  1. Introduction
  2. What is the object-fit property?
  3. Values of object-fit and their meanings
  4. How to use object-fit
  5. Conclusion

1. Introduction

In HTML, the size of an image is usually specified using the width and height attributes of the <img> tag. However, you can also perform more advanced resize operations using CSS. For that, you use the CSS object-fit property.


2. What is the object-fit property?

The object-fit property controls how the contents of a replaced element, such as an image, fit into the specified width and height. There are five values for this property.


3. Values of object-fit and their meanings

Here are the values of object-fit and their meanings:

  • fill: The content of the element is stretched to fit the specified size. The original aspect ratio is not retained.
  • contain: The content of the element is reduced or enlarged to fit within the specified size. The original aspect ratio is retained.
  • cover: The content of the element is reduced or enlarged to cover the specified size. The original aspect ratio is retained, but some content may be trimmed.
  • none: The content of the element is not resized and the original size is used as is.
  • scale-down: The smaller behavior of none or contain is applied.

4. How to use object-fit

Now, let's see how to resize images using each value of object-fit.

fill

<img src="image.jpg" style="object-fit: fill; width: 300px; height: 200px;">
Enter fullscreen mode Exit fullscreen mode

contain

<img src="image.jpg" style="object-fit: contain; width: 300px; height: 200px;">
Enter fullscreen mode Exit fullscreen mode

cover

<img src="image.jpg" style="object-fit: cover; width: 300px; height: 200px;">
Enter fullscreen mode Exit fullscreen mode

none

<img src="image.jpg" style="object-fit: none; width: 300px; height: 200px;">
Enter fullscreen mode Exit fullscreen mode

scale-down

<img src="image.jpg" style="object-fit: scale-down; width: 300px; height: 200px;">
Enter fullscreen mode Exit fullscreen mode

5. Conclusion

As you can see, you can easily resize images using HTML and CSS. With the object-fit property, you can choose the way to resize images as needed.

Remembering how each value of object-fit works will help you choose the best image resizing method for your web pages. So, Happy Coding!


That's it for now. I hope you find this article helpful. If you have any questions, please let me know in the comments. And if you think this article was useful, please give it a thumbs up!


Top comments (0)