Problem Statement
Which attributes are used to specify image dimensions in HTML?
Explanation
The width and height attributes are used to specify image dimensions in HTML. You can set these values in pixels by providing just a number, like width equals 300 height equals 200. These attributes tell the browser the image size before it loads, which helps prevent page layout shifts. When the browser knows the image dimensions in advance, it can reserve the correct amount of space, improving user experience and page performance. However, it is generally better to control image sizes using CSS rather than HTML attributes for more flexible and maintainable styling. If you set only width or only height, the browser will automatically calculate the other dimension to maintain the image's aspect ratio. Setting both width and height to values that do not match the original aspect ratio will distort the image. For responsive design, it is common to set max-width to 100 percent in CSS and let the height adjust automatically.
Code Solution
SolutionRead Only
<!-- Fixed size in pixels -->
<img src="photo.jpg" alt="Photo" width="300" height="200">
<!-- Only width (height auto) -->
<img src="banner.jpg" alt="Banner" width="800">
<!-- Better approach with CSS -->
<style>
.responsive-img {
max-width: 100%;
height: auto;
}
</style>
<img src="photo.jpg" alt="Photo" class="responsive-img">