The following rules apply when adding multiple layers of background properties in CSS:
- Backgrounds are stacked in an order;
background-*properties can be specified zero or one time per background;background-coloris 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:
layer-1.pngwill be stacked above all other images;layer-2.pngwill be in the middle;layer-3.pngwill 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.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.