EN
CSS - force image resize keeping aspect ratio
1
answers
3
points
I have a problem working with images with their aspect ratio.
For example:
<img src="image.jpg" width="400" height="200" alt="" />
Its height and width are already specified and now I want to add a CSS rule for images:
img {
max-width: 300px;
}
But for my image.jpg, I get width=300 and height=200.
How can I set images to be resized keeping their aspect ratios?
1 answer
3
points
The following CSS should solve your problem:
img {
display: block;
max-width: 300px;
max-height: 100px;
width: auto;
height: auto;
}
Practical example
The image inside the body is originally 225x225 pixels, but it is resized by the CSS to 100px height keeping aspect ratio (it means 100x100).
// ONLINE-RUNNER:browser;
<!DOCTYPE html>
<html>
<head>
<style>
img {
display: block;
max-width: 250px;
max-height: 100px;
width: auto;
height: auto;
}
</style>
</head>
<body>
<img height="225" width="225" src="https://dirask.com/static/bucket/1631898942509-VMYrnXyYZv--image.png" />
</body>
</html>
0 comments
Add comment