DEV Community

Cover image for This is how you make images Responsive in CSS
Dhairya Shah
Dhairya Shah

Posted on • Originally published at codewithsnowbit.hashnode.dev

This is how you make images Responsive in CSS

Hello Folks πŸ‘‹

What's up friends, this is SnowBit back here. I am a young passionate and self-taught frontend web developer and have an intention to become a successful developer.

Today, I am here with a cool CSS trick that can help and save you from getting it into trouble.

Let's go...

It is very important for a web developer to make mobile responsive images and fit all the content properly in the viewport.

Let's choose an image from Unsplash - (any of your choice)
img

Now, it's time to add the image to our HTML file

<img src="https://images.unsplash.com/photo-1644868731706-bdb6485f4274?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=930&q=80" class="img"/>
Enter fullscreen mode Exit fullscreen mode

Now let's get a sneak peek of output,

I guess you have tried to resize the image, haven't you?
here, you can notice the image is not responsive and it becomes uncomfortable 😱 to see it on mobile phones.

Now, let's bring our super-power πŸ”₯ of CSS and give it a gracious look.

  width: 100%;
  max-width: 400px;
  height: auto;
Enter fullscreen mode Exit fullscreen mode

Here we are giving the 100% width and independent height to the image, and here max-width property is completely optional

Here's the final output,


β€œWhitespace is never white.”

Thank you for reading, have a nice day!
Your appreciation is my motivation 😊 - Give it a like

Happy Coding!

Top comments (1)

Collapse
 
ferdau profile image
ferdau

Hi, I recommend looking into the "object-fit" property. Should end with even less lines of CSS ;)