Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 14

Styling Backgrounds with CSS

Recommended resources

Welcome to the next lesson in our journey through CSS! In the previous session, we deconstructed the CSS Box Model, learning how margin, padding, and border define the space that every element occupies. This understanding of an element as a "box" is the perfect foundation for today's topic.

This lesson focuses on what goes inside that box, specifically on its background. You will learn how to apply background colors and images, which are fundamental skills for creating visually engaging and well-structured websites. We will cover setting solid colors, adding images, and then dive into the essential properties for controlling those images: background-repeat, background-position, and background-size. By the end, you'll be able to transform plain elements into rich visual containers.

A Visual Overview of Background Properties

Before we dive into the details, take a look at the image below. It provides a quick visual reference for the various background properties we will be exploring in this lesson. Don't worry about understanding them all right now; just use it as a map for the journey ahead.

This image showcases a variety of CSS background properties, including color, image, repeat, position, size, gradients, and the use of multiple backgrounds on a single element.

Applying Solid Background Colors

The most straightforward way to style an element's background is to give it a solid color. This is incredibly useful for creating distinct sections, highlighting information, and establishing a color palette for your website.

You'll use the background-color property. As you learned in our lesson on text styling, you can use color names (red), hexadecimal codes (#ff0000), or RGB values (rgb(255, 0, 0)).

Setting Backgrounds & Gradients - Learn to Code HTML & CSS

This article by Shay Howe provides a clear and concise introduction to setting background colors.

Please read the first section, Adding a Background Color. Notice the background-color property and the example code. The text also mentions providing a "fallback" color when using semi-transparent rgba values for older browsers, which is a good professional practice to be aware of.

When you apply a background-color, it fills the entire area defined by the element's content, padding, and border. This is the first place you can see the box model you learned about in the last lesson in action.


Adding a Background Image

While colors are great, images open up a new world of design possibilities. You can use them for large "hero" sections, subtle patterns, or decorative icons. The property for this is background-image, and it uses a url() function to point to the image file.

One of the most common stumbling blocks for beginners is getting the file path in the url() function correct. Your CSS file is usually in a different folder than your HTML file and your images. The following video by Kevin Powell does a masterful job of explaining not only how to add a background image but also how to navigate your project's folder structure to link to it correctly.

HTML & CSS for Absolute Beginners: Background images

This video offers a practical guide to implementing background images, with a special focus on solving the common issue of incorrect file paths.

Please watch from the beginning until the end of the section on file paths. Pay close attention to the explanation of why you might need to use ../ to go "up" a directory from your CSS file to find the images folder. This is a crucial concept.


Controlling Background Images

Once you've added an image, you'll immediately notice that you need more control. By default, the browser will tile the image to fill the entire element, which is often not what you want. Let's look at the three most important properties for taming your background images.

  1. background-repeat: Controls if and how the image repeats.
  2. background-size: Controls the size of the image.
  3. background-position: Controls where the image is placed within the element.

Kevin Powell's video continues with clear explanations for each of these.

HTML & CSS for Absolute Beginners: Background images

This next segment of the video walks through the essential properties for controlling the appearance and placement of your background image.

Please watch the following three parts: Repeating: Start at this section on background-repeat. You'll learn about the default tiling behavior and how to change it with values like no-repeat, repeat-x, and repeat-y. Positioning: Continue with the part on background-position. This shows you how to move the image around using keywords like center, top right, or bottom left. Sizing: Finally, watch this crucial section on background-size. Focus on the difference between the cover and contain keywords. background-size: cover; is one of the most useful and common CSS declarations for creating modern, full-width image backgrounds. It ensures the image always covers the entire element, even if some of it gets cropped.

As Kevin Powell mentions at the end of that segment, it's vital to remember that background images are decorative. They do not have alt text and are invisible to screen readers. If an image contains important information, it should be an <img> tag in your HTML, not a background in your CSS.


Advanced Backgrounds and Shorthand

You now have the primary tools for handling backgrounds. To round out your knowledge, let's look at a few more powerful features and a convenient way to write your styles.

  • Gradients: CSS can create color gradients on the fly, and it treats them just like background images.
  • Multiple Backgrounds: You can layer several backgrounds on top of each other (e.g., a small icon over a large gradient).
  • Shorthand Property: You can combine all the properties we've discussed into a single, concise background property.

Setting Backgrounds & Gradients - Learn to Code HTML & CSS

Let's return to the Shay Howe article to explore these advanced topics and the shorthand property.

Please read the following three sections: Start with Shorthand Background Image Values. This demonstrates how to combine multiple properties into the background shorthand. This is the preferred way to write these styles in practice. Next, read the section on Designing Gradient Backgrounds. Focus on the linear-gradient() function. You don't need to memorize all the options, just understand that you can create a gradient by providing two or more colors. Finally, briefly review Using Multiple Background Images. This shows the syntax for layering backgrounds, which can be useful for more complex designs.


Practice Time

Let's apply these new properties to your project. Open your index.html and styles.css files.

  1. Body Background: Add a subtle background color to your entire page. In your styles.css, find the body selector and add a light gray color.

    body {
      /* ... keep existing styles ... */
      background-color: #f4f4f4;
    }
    
  2. Create a "Hero" Section: Let's create a new section in your index.html to practice with a background image. Add this div just after your <body> tag, before your <h1>.

    <div class="hero">
      <h2>Welcome to My Website</h2>
    </div>
    
  3. Style the Hero Section: Now, let's add a background image to this new div. For this exercise, you can use a placeholder image from a service or find a free one from a site like Unsplash or Pexels. Add the following to your styles.css:

    .hero {
      /* Replace with your image URL */
      background-image: url('https://images.unsplash.com/photo-1554629947-334ff61d85dc?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80');
      
      /* Make the image cover the area */
      background-size: cover;
      
      /* Center the image */
      background-position: center;
      
      /* Stop it from repeating */
      background-repeat: no-repeat;
      
      /* Add some space inside */
      padding: 100px 20px;
      
      /* Make the text readable */
      color: white;
      text-align: center;
    }
    

    Note: Here I've used the long-form properties for clarity. Try rewriting it using the background shorthand you just learned!

  4. Save and Refresh: Save both files and look at your index.html in the browser. You should see a large banner image at the top of your page with white text over it. Try resizing your browser window to see how background-size: cover keeps the image scaled beautifully.


Conclusion

You've now added another essential set of tools to your CSS arsenal. Being able to manipulate backgrounds is key to moving beyond plain, text-based documents and toward creating visually compelling web page layouts.

Key Takeaways:

  • Use background-color to apply solid colors to an element's background area.
  • Use background-image: url(...) to place an image in the background. Remember to get your file paths correct!
  • Control images with background-repeat, background-position, and background-size.
  • background-size: cover is your go-to property for making an image responsively fill an entire element.
  • Background images are for decoration; they are inaccessible to screen readers and should not convey critical information.
  • The background shorthand property allows you to set multiple background styles in a single line.

In our next lesson, we'll address a question that may have already started to pop up: What happens when two different CSS rules try to style the same element? We will explore CSS specificity, the set of rules the browser follows to decide which style declaration "wins" in a conflict.