How to Use Images as Backgrounds with CSS

| Coding Tutorials
Using Images as Backgrounds with CSS

As a new web designer, one very skill you'll need to master is using background images.

Depending on the design, you may need to completely fill a CSS container with an image, or sometimes the image will just partially fill the container.

In this post, we’ll show you three examples, using the CSS property background-size.

Base CSS

To display an image as background within a container, you need this sample CSS:

.container-class {
    background-image: url(path/to/image.jpg);
    background-repeat: no-repeat;
    background-position: center;
    width: 400px;
    height: 400px;
    border: 2px dashed #333;
}

  • Replace .container-class with the selector you want to target.
  • border and background-position properties are optional. We use them here to showcase the different results we’ll display below.

To define a specific size for the image, we’re missing the background-size property. Let’s talk about that in the next steps.

Example #1. Full width background, but no full height

In this case, we are using an image which is higher than it is wide.

Include the syntax below to make the background image go full width:

background-size: 100% auto;

In tthis example, notice how the image only covers the width, but not the height.

1

Example #2. Full height background, but no full width

In this case, we are using an image with bigger height than width.

Include the syntax below to make the background image go full height:

background-size: auto 100%;

In this example, notice how the image only covers the height, but not the width.

2

Example #3.. Full background

Include this syntax to make the background image go full. This is an automatic way to fill the complete container, no matter the image’s aspect ratio:

background-size: cover;

In this example, notice how the image covers the container. There are no empty spaces.

3

The list of background-size values

This is the complete list of background-size values:

  • auto - Default value.
  • length - As example: 100% auto or 400px auto. The first value is for the width, the second for the height.
  • cover - Cover the complete area.
  • contain - Scale the image to its biggest size.
  • initial - Set this propery to its default.
  • inherit - Inherited from the parent.

About the author

Valentín creates beautiful designs from amongst the tequila plants of Jalisco, Mexico. You can see Valentín's design work all over this site and you can often find him helping members in support.