You can set the width and height of an image in CSS using the width
and height
properties. These properties allow you to explicitly define the dimensions of the image element.
Using width
and height
Properties
The most direct way to control an image's size is by setting the width
and height
properties. These properties can accept values in various units, such as pixels (px), percentages (%), ems (em), or viewport units (vw, vh).
img {
width: 300px;
height: 200px;
}
This CSS code will force all <img>
elements to be 300 pixels wide and 200 pixels tall.
Maintaining Aspect Ratio
When setting both width
and height
, the image may become distorted if the new dimensions don't match the original aspect ratio. To maintain the aspect ratio, you can set either the width
or the height
property and let the browser automatically calculate the other dimension. A common approach is to set the width
and use height: auto;
.
img {
width: 300px;
height: auto; /* Browser calculates height to maintain aspect ratio */
}
Alternatively, you could set the height
and use width: auto;
.
Using max-width
and max-height
for Responsive Images
For responsive designs, it's often better to use max-width
and max-height
instead of fixed width
and height
. This allows the image to scale down if its container is smaller than the specified dimensions.
img {
max-width: 100%; /* Image will not exceed the width of its container */
height: auto;
}
Setting max-width
to 100%
ensures the image never overflows its container, while height: auto;
maintains the aspect ratio.
Similarly, you can constrain the height while allowing the width to adjust:
img {
width: auto;
max-height: 500px;
}
Object-fit property
The object-fit
property offers more control over how the image is resized within its defined width and height. Possible values include:
cover
: The image is scaled to fill the entire box. It might be cropped to fit.contain
: The image is scaled to fit inside the box, maintaining its aspect ratio. Empty space may appear.fill
: The image is stretched to fill the entire box, potentially distorting the image.none
: The image is not resized.scale-down
: The image is scaled down tocontain
if it is larger than the box, otherwise, it is displayed at its original size.
img {
width: 200px;
height: 150px;
object-fit: cover; /* Example: image will cover the entire area */
}
Summary
In summary, use width
and height
for fixed dimensions, max-width
and max-height
for responsive behavior, and object-fit
for precise control over how the image is resized within its container. Remember to consider aspect ratio to avoid distortion.