The Wayback Machine - https://web.archive.org/web/20250118021259/https://www.geeksforgeeks.org/set-the-size-of-background-image-using-css/
Open In App

Set the size of background image using CSS ?

Last Updated : 19 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Setting the size of a background image using CSS allows you to control how the image fits within an element. By using the background-size property, you can specify the width and height, ensuring the image scales appropriately for responsive design.

Syntax:

background-size: width height;

Note:

  • If the first value is omitted then the image takes its original width.
  • If the second value is omitted then the image takes its original height.

Example 1: In this example, we use CSS to set a background image in a <div> with specified dimensions. The background-size property ensures the image fits the container of 400px width and 200px height.

html
<!DOCTYPE html>
<html>

<head>
    <title>
        Set the size of background image
    </title>

    <style>
        #myDiv {
            height: 200px;
            width: 400px;
            background:
                url(
"https://media.geeksforgeeks.org/wp-content/uploads/gfgbg.png");
            background-size: 400px 200px;

        }
    </style>
</head>

<body>
    <div id="myDiv"></div>
</body>

</html>

Output:

Example 2: In this example we sets a background image in a <div> with dimensions 400px by 200px. The background-size property adjusts the image size to 70% of the container’s width while preventing repetition.

html
<!DOCTYPE html>
<html>

<head>
    <title>
        Set the size of background image
    </title>

    <style>
        #myDiv {
            height: 200px;
            width: 400px;
            background:
                url(
"https://media.geeksforgeeks.org/wp-content/uploads/gfgbg.png");

            /* Set the background-size in percentage */
            background-size: 70%;
            background-repeat: no-repeat;
        }
    </style>
</head>

<body>
    <div id="myDiv"></div>
</body>

</html>

Output:

Dive deep into the world of JavaScript with our JavaScript Full Course Online, offering everything from the basics to advanced techniques. Learn how to build interactive websites, optimize your code, and earn a certification to showcase your skills.

Take the Three 90 Challenge! Complete 90% of the course in 90 days, and earn a 90% refund. Push your limits and stay motivated as you work towards mastering JavaScript. Join now and get started on your JavaScript learning journey!


Next Article
Article Tags :

Similar Reads

three90RightbarBannerImg