How to set the size of the background image with JavaScript?

JavascriptWeb DevelopmentFront End Scripts

To set the size of the background image in JavaScript, use the backgroundSize property. It allows you to set the image size for the background.

Example

You can try to run the following code to learn how to set the size of the background image:

Live Demo

<!DOCTYPE html>
<html>
   <head>
      <style>
         #box {
            border: 2px dashed blue;
            width: 600px;
            height: 400px;
            background: url('https://www.tutorialspoint.com/videotutorials/images/coding_ground_home.jpg') no-repeat;
         }
      </style>
   </head>
   <body>
      <button onclick="display()">Set size of background image</button>
      <div id="box">
      </div>
      <script>
         function display() {
            document.getElementById("box").style.backgroundSize = "150px 200px";
         }
      </script>
   </body>
</html>
raja
Published on 27-Feb-2018 10:15:41
Advertisements