Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to create a responsive image with CSS?
Responsive images automatically scale with the screen size, ensuring optimal display across all devices. The key CSS properties for creating responsive images are width, max-width, and height.
Syntax
img {
max-width: 100%;
height: auto;
}
Method 1: Using max-width Property
The most common approach uses max-width: 100% to ensure the image never exceeds its container width −
<!DOCTYPE html>
<html>
<head>
<style>
.responsive-img {
max-width: 100%;
height: auto;
display: block;
margin: 20px auto;
}
.container {
width: 80%;
margin: 0 auto;
border: 2px solid #ddd;
padding: 20px;
}
</style>
</head>
<body>
<div class="container">
<h2>Responsive Image Example</h2>
<img src="/css/images/css-mini-logo.jpg" alt="CSS Logo" class="responsive-img">
<p>Resize the browser window to see the image scale.</p>
</div>
</body>
</html>
An image that scales down when the browser window is resized but never exceeds its original size. The image maintains its aspect ratio and is centered within a bordered container.
Method 2: Using width Property
Setting width: 100% makes the image fill its container completely −
<!DOCTYPE html>
<html>
<head>
<style>
.full-width-img {
width: 100%;
height: auto;
max-width: 600px;
}
.image-container {
width: 50%;
margin: 20px auto;
border: 2px solid #007bff;
padding: 15px;
}
</style>
</head>
<body>
<div class="image-container">
<h3>Full Width Responsive Image</h3>
<img src="/css/images/css-mini-logo.jpg" alt="CSS Logo" class="full-width-img">
</div>
</body>
</html>
An image that fills the entire width of its container (50% of the viewport) and scales proportionally. The image has a maximum width of 600px to prevent excessive stretching.
Key Properties
| Property | Value | Purpose |
|---|---|---|
max-width |
100% |
Prevents image from exceeding container width |
width |
100% |
Makes image fill the container completely |
height |
auto |
Maintains aspect ratio while scaling |
Best Practices
Always include the viewport meta tag for proper mobile responsiveness −
<meta name="viewport" content="width=device-width, initial-scale=1">
Conclusion
Use max-width: 100% and height: auto for the most flexible responsive images. This ensures images scale down on smaller screens while maintaining their aspect ratio and never exceeding their original dimensions.
Advertisements
