CSS `background-origin`: Precisely Positioning Background Images
Master precise background image placement in your CSS stylesheets using the `background-origin` property. This tutorial explains how to control background image positioning relative to the content area, padding, and border of an element, enabling you to create unique and sophisticated visual effects.
Controlling Background Image Positioning with CSS `background-origin`
Understanding `background-origin`
The CSS `background-origin` property specifies the area from which a background image is positioned. This affects how the background image is drawn relative to the element's content, padding, and border. It's a useful tool for fine-tuning background image placement and creating specific visual effects.
Note that `background-origin` does not work when `background-attachment: fixed;` is used. Also, `background-origin` differs from `background-clip`, which controls the clipping region for the background, not its starting position.
`background-origin` Property Values
The `background-origin` property can have one of these values:
Value | Description |
---|---|
padding-box |
(Default) The background image starts from the top-left corner of the padding box (inside padding). |
border-box |
The background image starts from the top-left corner of the border box (inside border). |
content-box |
The background image starts from the top-left corner of the content box (inside content). |
initial |
Sets the property to its default value (padding-box ).
|
inherit |
Inherits the value from its parent element. |
Examples of `background-origin`
These examples demonstrate how different `background-origin` values affect background image positioning. Each example would require a corresponding HTML element with a background image applied; the CSS would control the `background-origin` for that element.
Example 1: `padding-box`, `border-box`, `content-box`
This example illustrates the visual difference between positioning the background image relative to the padding box, border box, and content box. Note that the apparent size of the box might change depending on the specified value.
Example 2: Multiple Background Images
This example shows how to set different `background-origin` values for multiple background images, demonstrating how each background image will be positioned independently.
Example 3: `initial` and `inherit`
This illustrates how `initial` resets to the default value (`padding-box`), and `inherit` takes the value from the parent element.