How to change image size in CSS

Sometimes, there is a need to adjust an image to specific dimensions. To resize an image, we can set the width and height values accordingly. A popular approach is to employ max-width: 100%; and height: auto; to ensure that oversized images stay within the boundaries of their container. While the CSS properties max-width and max-height offer a more effective solution, they may not be compatible with all browsers.

Another method of adjusting the image size is through the application of the object-fit property, which adjusts the image accordingly. This particular CSS attribute dictates the resizing behavior of a video or an image to conform to its designated container. It determines the method by which an element is accommodated within a container of predefined dimensions.

The object-fit attribute is typically used with images or videos. It determines how a particular element adjusts to the dimensions of its container. There are five primary options available for the object-fit attribute: fill, contain, cover, none, and scale-down, as well as initial and inherit. The default setting for this attribute is "fill".

Example

In this instance, we are adjusting the image size by employing the max-width: 100%; and height: auto; attributes.

Example

<!DOCTYPE html>

<html>

<head>

<title>cell padding</title>

<style>

div {

width: auto;

text-align: center;

padding: 15px;

border: 3px solid red;

}

img {

max-width: 100%;

height: auto;

}

</style>

</head>

<body>

<div>

<img src= "https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image">

</div>

</body>

</html>

Output

Example

In this instance, we are utilizing the object-fit: cover; CSS property.

Example

<!DOCTYPE html>

<html>

<head>

<style>

div {

width: 300px;

height: auto;

text-align: center;

padding: 15px;

border: 3px solid red;

}

img {

object-fit: cover;

}

</style>

</head>

<body>

<div>

<img src= "https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image" width = "300" height = "300">

</div>

</body>

</html>

Output

In the previous instance, we employed the cover value within the object-fit property. Just like the previous scenario, we have the option to utilize the remaining values of the object-fit property to adjust the image size.

Input Required

This code uses input(). Please provide values below: