The Background Shorthand Property

Shorthands exist to make declarations faster and easier. The background shorthand isn't left out too. In this lesson, we will take a look at how the CSS backkground shorthand really works

The background shorthand property like other shorthands, can be a life saver. When you have a lot of background declarations, it easier to have them declared in one statement.

For example, consider the code below:

.bg {
  background-image: url('path/to/image.png');
  background-position: 50% 50%;
  background-size:  cover;
  background-repeat: no-repeat;       
}


Using the background shorthand, it becomes this:

.bg {
    background: url('path/to/image.png') 50% 50%/cover no-repeat;
}

Isn’t that awesome?

How it Works

As seen in the example above, the background property takes in background properties and sets them in one declaration.

The background properties include, url background-position background-size background-repeat background-origin background-clip and background-attachment

Oh my god, what a long list!



Must I Follow an exact sequence of properties?

The values of the individual background properties in the background shorthand can be shuffled as you deem fit.

The one rule to always remember is that the background-size property must be specified after the background-position property.
They must also be separated with the ‘/’ character.

You cannot specify the background size in the shorthand property unless you also specify the background position, otherwise the declaration is invalid.



My Personal Recommendation

I do have a sequence I follow - just to keep me sane. I have an acronym that has helped me too. Here it is: UPS ROCA

What?

Get hands-on with 1200+ tech skills courses.