CSS Backgrounds

Hey friends 👋 welcome back. In the last lesson, we learned about borders, margins, and padding — the CSS box model. Today, we are going to make our pages more exciting with CSS backgrounds.

With CSS, you can style the background of any element using colors, images, gradients, and patterns. Let’s dive in.

Background Color

The simplest background is just a solid color. You can set it using the background-color property.

<!DOCTYPE html> <html> <head> <title>CSS Background Color</title> <style> body { background-color: lightblue; } h1 { background-color: yellow; } p { background-color: pink; } </style> </head> <body> <h1>Heading with Yellow Background</h1> <p>This paragraph has a pink background.</p> </body> </html>

Background Image

You can also add an image as a background using background-image.

<!DOCTYPE html> <html> <head> <title>CSS Background Image</title> <style> body { background-image: url("background.jpg"); } </style> </head> <body> <h1>Page with a Background Image</h1> <p>This page uses an image in the background.</p> </body> </html>

By default, the image repeats both horizontally and vertically.

Controlling Backgrounds

You can control how the background behaves using:

  • background-repeat → values: repeat, repeat-x, repeat-y, no-repeat.

  • background-position → values: left, right, center, top, bottom.

  • background-size → values: auto, cover, contain, or exact sizes like 100px 200px.

  • background-attachment → values: scroll or fixed.

Example:

<!DOCTYPE html> <html> <head> <title>CSS Background Control</title> <style> body { background-image: url("background.jpg"); background-repeat: no-repeat; background-size: cover; background-position: center; background-attachment: fixed; } </style> </head> <body> <h1>Cool Background Effects</h1> <p>Scroll this page to see the fixed background effect.</p> <p>With CSS, you can make your pages more attractive.</p> </body> </html>


This code makes the background image cover the whole page, stay centered, and remain fixed even when scrolling.

Background Shorthand

Instead of writing many properties, you can combine them in one line:

background: url("image.jpg") no-repeat center/cover fixed;

This is called shorthand, and it makes your CSS cleaner.

Try It Yourself

Create a new file called backgrounds.html. Use CSS to:

  • Give your page a solid color background.

  • Add a heading with a different background color.

  • Experiment with a background image — try cover, contain, and fixed.

See how each property changes the design.

Great job 🎉 You just learned about CSS backgrounds. In the next tutorial, we will explore CSS Lists and Text Decoration, where we’ll style bullet points, numbered lists, and make our text even more creative. 🚀