Search code examples
javascripthtmlcssbackgroundbackground-image

How to stop background image from losing quality/ blurring on screen resize


When I was creating a website I noticed that my background was blurred because of the screen size I want that to stop so I can be happier with my website and visitors will be better. Also, my background looks fine on the original image size of the bg. Here is my code and the code pen.

function openNav() {
  document.getElementById("myNav").style.width = "100%";
}

function closeNav() {
  document.getElementById("myNav").style.width = "0%";
}
body {
  background-image: url("https://i.dlpng.com/static/png/6750263_preview.png");
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-size: cover;
  font-family: "Lato", sans-serif;
}

.overlay {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: rgb(0, 0, 0);
  background-color: rgba(0, 0, 0, 0.9);
  overflow-x: hidden;
  transition: 0.5s;
}

.overlay-content {
  position: relative;
  top: 25%;
  width: 100%;
  text-align: center;
  margin-top: 30px;
}

.overlay a {
  padding: 8px;
  text-decoration: none;
  font-size: 36px;
  color: #818181;
  display: block;
  transition: 0.3s;
}

.overlay a:hover,
.overlay a:focus {
  color: #f1f1f1;
}

.overlay .closebtn {
  position: absolute;
  top: 20px;
  right: 45px;
  font-size: 60px;
}

@media screen and (max-height: 450px) {
  .overlay a {
    font-size: 20px;
  }
  .overlay .closebtn {
    font-size: 40px;
    top: 15px;
    right: 35px;
  }
}
<!doctype html>
<html>
<span style="font-size:30px;cursor:pointer" onclick="openNav()">&#9776;</span>
<div id="myNav" class="overlay">
  <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
  <div class="overlay-content">
    <a href="#">Home</a>
    <a href="#">Shop</a>
    <a href="#">My Projects</a>
    <a href="#">Contact</a>
    <a href="#">About</a>
  </div>
</div>

</html>

https://codepen.io/Javscript/pen/XWMwNYN?editors=1000


Solution

  • You can media queries in your CSS to load a larger image as appropriate to the users screen size.

    body {
      background-image: url("/image.png");
    }
    
    @media screen and (min-width: 640px) {
      body {
        background-image: url("/image-small.png");
      }
    }
    
    @media screen and (min-width: 768px) {
      body {
        background-image: url("/image-medium.png");
      }
    }
    
    @media screen and (min-width: 1024px) {
      body {
        background-image: url("/image-large.png");
      }
    }
    

    You will need to host the image in multiple sizes for this to work.

    You can read more about media queries here: https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries