HTML Image Dimensions and Aspect Ratio
Declare dimensions
Use integer CSS-pixel values without units for width and height. Providing both in the correct intrinsic ratio gives the browser sizing information before the resource loads. It can reduce layout shifts, but does not guarantee that the page never shifts.
<img src="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22320%22%20height%3D%22160%22%20viewBox%3D%220%200%20320%20160%22%3E%3Crect%20width%3D%22320%22%20height%3D%22160%22%20fill%3D%22%23dbeafe%22%2F%3E%3Cpath%20d%3D%22M0%20160%20L160%2032%20L320%20160Z%22%20fill%3D%22%23166534%22%2F%3E%3C%2Fsvg%3E" alt="Green hill" width="320" height="160">The image has a 2:1 width-to-height ratio.
Scale without stretching
CSS is the styling language used to control layout. In this small preview, max-width: 100% limits the image to its container and height: auto preserves its ratio. You do not need to know CSS beyond these two declarations yet.
<div style="width: 160px"> <img src="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22320%22%20height%3D%22160%22%20viewBox%3D%220%200%20320%20160%22%3E%3Crect%20width%3D%22320%22%20height%3D%22160%22%20fill%3D%22%23dbeafe%22%2F%3E%3Cpath%20d%3D%22M0%20160%20L160%2032%20L320%20160Z%22%20fill%3D%22%23166534%22%2F%3E%3C%2Fsvg%3E" alt="Green hill" width="320" height="160" style="max-width: 100%; height: auto"></div>The 320 by 160 image is displayed at 160 by 80 pixels.
Use the correct ratio
Changing both dimensions to an unrelated ratio can stretch a picture. Match the source proportions unless distortion is deliberate. For different crops, supply sizing information appropriate to the selected image.
<img src="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22320%22%20height%3D%22160%22%20viewBox%3D%220%200%20320%20160%22%3E%3Crect%20width%3D%22320%22%20height%3D%22160%22%20fill%3D%22%23dbeafe%22%2F%3E%3Cpath%20d%3D%22M0%20160%20L160%2032%20L320%20160Z%22%20fill%3D%22%23166534%22%2F%3E%3C%2Fsvg%3E" alt="Green hill" width="240" height="120">Scaling both dimensions by the same factor keeps the hill proportional.
Practice and next steps
Calculate the height for a 320 by 160 image displayed at 200 pixels wide.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTML Image Dimensions and Aspect Ratio — Knowledge Check
Check the core concepts from this lesson.
A 400×200 image is displayed at width 100. Which height preserves its ratio?
Why declare width and height with a correct ratio?
What does height: auto do when a proportional image is scaled in width?
A 600 by 300 image has CSS width 300px and height auto. What height preserves the ratio?
What must the declared width and height reflect to reserve suitable space?