DEV Community

Cindy
Cindy

Posted on

Responsive Background Image Using CSS

Recently, I've been working on my portfolio (shameless plug 😅) and learning about how to make it more responsive. A responsive website will adapt to a change in screen size so that the website will nicely display the page content.

You can create a responsive background image with just CSS.

HTML

<div class="bg"></div>

CSS

.bg {
  height: 100vh;
  min-height: 500px;
  background-image: url(images/bg.jpeg);
  background-position: center center;
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-size: cover;
  background-color: #1d3557;
}
  • height: 100vh means the height of this bg element to be 100% of the viewport height
  • min-height: 500px sets the minimum height of the element
  • background-position: center center will center the image vertically and horizontally at all times
  • background-repeat: no-repeat prevents the image from repeating and creating the tiled look
  • background-attachment: fixed keeps the image fixed in the viewport so even when you scroll down it won't move. Creates the parallax scrolling effect where the background content moves at a different speed than the foreground content while scrolling. When scrolling, it looks like the rest of the website scrolls on top of the background image.
  • background-size: cover will make the background image resize to fit the size of the screen
  • background-color: #1d3557 will set a background color that will be displayed while the background image is loading

This code worked well on laptops, but on iPhones and iPads (haven't tested on other types of devices), the background image was very zoomed-in, leaving me with a pixelated image.

After some research, I learned that the problem was with the background-attachment property. Some mobile devices have a problem with background-attachment being fixed, so to fix this, you just need to use media queries to turn off the parallax effect for mobile devices by setting background-attachment to scroll.

/* Increase/decrease the pixels if needed */
/* For all devices with a screen size smaller than 1366px, the background-attachment property will be scroll instead of fixed */

@media only screen and (max-device-width: 1366px) {
  .bg {
    background-attachment: scroll;
  }
}

Now, you should be able to see the full background image on all devices instead of a pixelated corner of the image!

Top comments (1)

Collapse
 
isajal07 profile image
Sajal Shrestha

Thanks, Cindy. I will soon add this to my portfolio as well.