What Rules Apply When Specifying Multiple Backgrounds in CSS?

Learn about the rules for adding multi backgrounds in CSS

The following rules apply when adding multiple layers of background properties in CSS:

  1. Backgrounds are stacked in an order;
  2. background-* properties can be specified zero or one time per background;
  3. background-color is only permitted on the last layer.

Backgrounds Are Stacked in an Order

When you specify multiple backgrounds using in CSS, the backgrounds are stacked in an order — where the first background appears on top and the last background is shown in the back. For example:

background:
    url('layer-1.png') no-repeat,
    url('layer-2.png') repeat-x,
    url('layer-3.png') repeat-x,
;

In the example above, the stacking order of backgrounds will be as follows:

  1. layer-1.png will be stacked above all other images;
  2. layer-2.png will be in the middle;
  3. layer-3.png will appear behind all other images.

background-* Properties Can Be Specified Zero or Once per Background

When specifying multiple backgrounds, all background-* properties can be specified zero or one time per background layer. The background-color property is an exception to the rule (as it's only permitted on the last layer). This means that you can specify the following background-* properties in each background layer only once:

  • background-attachment;
  • background-clip;
  • background-image;
  • background-origin;
  • background-position;
  • background-repeat;
  • background-size.

For example:

background:
    url('layer-1.png') top left / 100% auto no-repeat,
    url('layer-2.png') repeat-x padding-box,
    #ccc url('layer-3.png') left 15px top,
    /* ... */
;

Although, generally, you can specify individual properties on each layer in any order you want, still there are some exceptions when using the background shorthand property.

background-color Is Only Permitted on the Last Layer

The background-color property only applies to the final background layer, for example:

background:
    url('layer-1.png') no-repeat,
    url('layer-2.png') repeat-x,
    #ccc url('layer-3.png') repeat-x,
    /* ... */
;

Other background properties, however, can be specified/applied (zero or one times) on each layer.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.