Open In App

How to Add Background Image in CSS ?

Last Updated : 29 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Adding a background image to a webpage can enhance its aesthetic appeal and make it more engaging for users. CSS (Cascading Style Sheets) provides several properties to easily set and customize background images. In this article, we will explore different approaches to add background images in CSS.

1. Using the background-image Property

The simplest way to add a background image is by using the background-image property. You can specify the image URL within the url() function.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <style>
        body {
            background-image: url(
        }
    </style>
</head>
  
<body>
    <h1>Welcome to GeeksforGeeks</h1>
</body>
  
</html>


Output

background-image

2. Setting Background Size

You can control the size of the background image using the background-size property. Common values include cover (to cover the entire element without stretching), contain (to fit the image within the element), and specific dimensions (like 100px 200px).

HTML




<!DOCTYPE html>
<html>
  
<head>
    <style>
        body {
            background-image: url(
            background-size: cover;
        }
    </style>
</head>
  
<body>
    <h1>Welcome to GeeksforGeeks</h1>
</body>
  
</html>


Output

background-image-2

3. Positioning the Background Image

The background-position property allows you to position the background image within the element. You can use keywords like top, bottom, left, right, or specific coordinates.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <style>
        body {
            background-image: url(
            background-position: center;
            background-repeat: no-repeat;
        }
    </style>
</head>
  
<body>
    <h1>Welcome to GeeksforGeeks</h1>
</body>
  
</html>


Output

background-image-3

4. Repeating Background Images

If your background image is smaller than the element, you can control its repetition using the background-repeat property. Values include repeat, repeat-x, repeat-y, and no-repeat.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <style>
        body {
            background-image: url(
            background-repeat: repeat-x;
        }
    </style>
</head>
  
<body>
    <h1>Welcome to GeeksforGeeks</h1>
</body>
  
</html>


Output

background-image-4



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads