You can resize an image in HTML primarily by using the width
and height
attributes within the <img>
tag. These attributes define the dimensions that the image should occupy in the browser.
Using width
and height
Attributes
The simplest method is to directly specify the desired width and height using the width
and height
attributes.
<img src="image.jpg" width="500" height="300" alt="Resized Image">
In this example, the image "image.jpg" will be displayed with a width of 500 pixels and a height of 300 pixels. Keep in mind that the browser will stretch or shrink the image to fit these dimensions, potentially affecting image quality if the aspect ratio is not maintained.
CSS for Resizing (Recommended)
While width
and height
attributes work, using CSS offers greater flexibility and control. Here's how:
-
Inline Styles:
<img src="image.jpg" style="width: 500px; height: 300px;" alt="Resized Image">
-
Internal/Embedded Styles (within
<style>
tag in the<head>
):<!DOCTYPE html> <html> <head> <style> img { width: 500px; height: 300px; } </style> </head> <body> <img src="image.jpg" alt="Resized Image"> </body> </html>
-
External Stylesheet (linked in the
<head>
):-
In your CSS file (e.g.,
style.css
):img { width: 500px; height: 300px; }
-
In your HTML:
<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="style.css"> </head> <body> <img src="image.jpg" alt="Resized Image"> </body> </html>
-
Maintaining Aspect Ratio with CSS:
To maintain the original aspect ratio of the image while resizing, you can use width
or height
and set the other dimension to auto
.
img {
width: 500px; /* Only specify width */
height: auto; /* Height will adjust automatically */
}
Or:
img {
width: auto;
height: 300px; /* Only specify height */
}
Using max-width
and max-height
:
To ensure that the image does not exceed certain dimensions, use max-width
and max-height
.
img {
max-width: 100%; /* Image will not be wider than its container */
height: auto;
}
This is especially useful for responsive designs.
Summary
Resizing images in HTML is achieved either directly with width
and height
attributes in the <img>
tag, or, more flexibly, through CSS styles. CSS provides more control, particularly regarding aspect ratio maintenance and responsive design implementation.