Images are an important part of any website, which is why it's necessary to make it responsive. In this small blog, we will talk about how to make it so.
This tutorial uses three files named index.html, style.css, and the image that you will use.
-
Get Started with HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Make Image Responsive in css</title> <link rel="stylesheet" href="style.css"> </head> <body> <img src="pexels-luis-gomes-546819.jpg" alt="sample image" class="image"> </body> </html>
Our HTML is pretty straightforward. It's just an <img> tag with the src, alt, and class attributes. Just make sure the value of your src is correct.
-
Add CSS
* { padding: 0; margin: 0; box-sizing: border-box; } .image { width: 65%; }
We can make an image responsive by setting the width to a relative unit such as % and the height to auto.
In our .image class, we set the width to 65%, and because the default value of height is auto, we don't need to specify it.
-
Add Media Query (optional)
@media screen and (max-width: 992px) { .image { width: 100%; } }
Media Query is optional when making the image responsive, but if you need to make the image width different on different devices, you can do so by adding media query.
What's coming?
In my next post, I will be creating a blog layout in CSS. I will combine my previous posts Responsive Navigation Bar, Responsive Two-Column Layout, and this post.