How do I use css background-size?



  • This article demonstrates the various values of the CSS background-size element. It shows the use of pixel values, percentage value and the contain and cover values.

    Using the demo code.

    HTML.

    ...
     <div>
            <h1>Good Morning HTML</h1>
        </div>
    ...
    

    CSS.

    ...
     div {
               width: 500px;
               height: 500px;
               border: 5px solid blueviolet;
               margin: 100px auto;
               color: #fff;
               background-image: url(images/rose.jpeg);
               background-repeat: no-repeat;           
          }
    ...
    

    Without the background-size CSS property, the image covers the entire width and height of the div element. In this example the image width/height is 500px by 500px and the element has the same dimensions.

    8db7ef28-b030-4eca-9192-82174227c870-image.png

    Adding the background-size property and making it 100px, and height 50px

    ...
     div {
               width: 500px;
               height: 500px;
               border: 5px solid blueviolet;
               margin: 100px auto;
               color: #fff;
               background-image: url(images/rose.jpeg);
               background-repeat: no-repeat; 
               background-size: 100px 50px;          
          }
    ...
    

    The result is a stretched looking image.
    52e777f8-67d6-4ba0-b991-84cc13dae693-image.png

    If we only use the width for the background-size the image become proportionate. The height become value auto by default.

    db61b798-d88e-40b4-81ed-3b75e0c85832-image.png

    Using percentage values for width and height result in the same look and if only one value is used either for width or height, then auto is applied for the second value by default.

    Using the background-size contain value.

    Changing the height value for demonstration purposes.

    ...
     div {
               width: 500px;
               height: 600px;
               border: 5px solid blueviolet;
               margin: 100px auto;
               color: #fff;
               background-image: url(images/rose.jpeg);
               background-repeat: no-repeat;
               background-size: contain;
           }
    ...
    

    You can see that using background-size: contain; the image takes up the entire width of the element.

    ac5d395f-efc8-4fae-855d-c1f7837e81c1-image.png

    Using the background-size contain value.

    Using background-size: cover; the image fit the entire width and height of the element.

    8a6f859b-7708-414f-b1bc-95d97540e178-image.png

    Using background-size: 100% 100%; the image fit the entire width and height of the element, but will look stretched.


Log in to reply
 

© Lightnetics 2024