DEV Community

Abu Bakar Wase
Abu Bakar Wase

Posted on

The Best Way to make image/background responsive using CSS

There are several ways to make image background responsive but I am going to tell you the very best way to get this done.

So before diving into those properties, I want to explain the thought process behind this. In general, our browsers try to fit the image inside the viewport. To get this done they try to fit the whole image according to viewport which makes the image lose its height to width ratio. Hence results in a poor image.

Due to this behavior, the mess of poor image started. To avoid this mess we need to figure out some behavior in which image starts to adjust itself according to the viewport by cropping out the extra part of the image.

To get this done we give these properties to the block having image/background-image

{
height: 100vh;
background-image: url(../img/hero.jpg);
background-size: cover;
background-position: top;
}

So what we are doing there? Let's discuss this one by one

  • height: 100vh this will make the image take full height of the viewport like it will adjust itself according to tot the height of the monitor/screen.

-background-image: url('path of your image')
just to give a path

  • background-size: cover;
    The actual magic happens when you give cover as a size. Cover has the ability to crop out the extra part of the image to keep the image in its actual resolution.
    But things are not this simple, cover actually clips the image from all the directions hence on the smaller screens only a very little part of the image will be available. To address this ratio base clipping issue we need to add another property.

  • background-position: top;
    This will fix the image to the stated property, i.e top, bottom, left, right. This will crop the image with one side fix and help us to keep the main content of the image visible all the time.

Top comments (0)