Usage of background property in CSS

The background property in CSS is a shorthand property that allows you to set multiple background-related properties in a single declaration. It can include background color, image, position, size, repeat behavior, and attachment.

Syntax

background: [color] [image] [repeat] [attachment] [position] / [size];

Individual Background Properties

The background shorthand can include any combination of these properties:

  • background-color - Sets the background color
  • background-image - Sets the background image
  • background-repeat - Controls image repetition
  • background-attachment - Controls scrolling behavior
  • background-position - Sets image position
  • background-size - Controls image size

Example: Background with Image

<!DOCTYPE html>
<html>
<head>
    <style>
        .background-example {
            background: url('/images/pattern1.gif') repeat fixed;
            padding: 20px;
            color: #333;
            border: 1px solid #ccc;
        }
    </style>
</head>
<body>
    <p class="background-example">
        This paragraph has a fixed repeated background image that won't scroll with the content.
    </p>
</body>
</html>

Example: Background with Color and Position

<!DOCTYPE html>
<html>
<head>
    <style>
        .color-background {
            background: #f0f8ff url('/images/logo.png') no-repeat center top;
            height: 200px;
            padding: 20px;
        }
        .gradient-background {
            background: linear-gradient(to right, #ff7e5f, #feb47b);
            color: white;
            padding: 15px;
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <div class="color-background">
        Background with color and centered image at top
    </div>
    <div class="gradient-background">
        Background with gradient colors
    </div>
</body>
</html>

Common Background Values

Property Common Values Description
repeat repeat, no-repeat, repeat-x, repeat-y Controls image repetition
attachment scroll, fixed, local Controls scrolling behavior
position center, top, bottom, left, right Sets image position

Multiple Backgrounds

<!DOCTYPE html>
<html>
<head>
    <style>
        .multiple-bg {
            background: 
                url('/images/overlay.png') repeat,
                url('/images/main-bg.jpg') no-repeat center,
                #ffffff;
            height: 150px;
            padding: 20px;
        }
    </style>
</head>
<body>
    <div class="multiple-bg">
        Element with multiple background layers
    </div>
</body>
</html>

Conclusion

The CSS background property is a powerful shorthand that simplifies styling by combining multiple background properties in one declaration. Use it to create visually appealing layouts with colors, images, and gradients efficiently.

Updated on: 2026-03-15T23:18:59+05:30

121 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements