How to Set the Size of the Background-image

Background images give our website uniqueness and visually appeal to users. The size of the background-image has huge importance.

If you want to set the size of your background-image, you are in the right place. For that, you need to use the background-size property. In this snippet, we’ll show you how to do that.

Let’s see an example and try to discuss each part of the code together.

Create HTML

  • Create an <h2> tag and put a title in it.
  • Create a <div> tag with the id name "image".
<body>
  <h2>Set the size of background image</h2>
  <div id="image"></div>
</body>

Add CSS

  • Set the height and width of the "image".
  • Add the URL of your image with the background property.
  • Set the size of the image with the background-size property.
#image {
  height: 200px;
  width: 200px;
  background: url("/uploads/media/default/0001/02/55a2f152f59bf42a99b576d44a4578ec9daa0ab6.png");
  background-size: 200px 200px;
}

You can change the size of your image by using percentages. In our example, we use the length value where the first value sets the width and the second one sets the height.

Let’s bring the code parts together and see the result!

Example of setting the background-image size using pixels:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      #image {
        height: 200px;
        width: 200px;
        background: url("/uploads/media/default/0001/02/55a2f152f59bf42a99b576d44a4578ec9daa0ab6.png");
        background-size: 200px 200px;
      }
    </style>
  </head>
  <body>
    <h2>Set the size of background image </h2>
    <div id="image"></div>
  </body>
</html>

Result

Let’s see another example where we use percentages for setting the background image size.

Example of setting the background-image size using percentages:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      body {
        background-image: url("https://images.unsplash.com/photo-1523800503107-5bc3ba2a6f81?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=80");
        background-size: 70% 400%;
        background-repeat: no-repeat;
        color:#cccccc;
      }
    </style>
  </head>
  <body>
    <h2>Background image size example.</h2>
    <p>Here can be any information.</p>
  </body>
</html>

Here, we used the background-repeat property with the "no-repeat" value. The background-repeat property defines how the background image must be repeated. When you set the "no-repeat" value, the background image is not repeated.

Do you find this helpful?

Related articles