# CSS background-attachment

Aug. 8, 2018 530

The background-attachment property specifies whether the background image scrolls with the element or its content, or remains fixed.

CSS

background-attachment: value;


## Values

scroll : Background image is fixed relative to the element. If the element's content scroll, it does not scroll. This is the default value.

local : Background image is fixed relative to the element's content. If the element's content scrolls, then the background image of the element will also scroll.

fixed : Background image is fixed relative to the viewport. It does not scroll with the element or its content. (Viewport is the visible area of a web page, and is different for different devices)

initial : Sets the default value of the property.

inherit : Inherits the value from parent element.

## Examples

See the Pen background-attachment examples by Aakhya Singh (@aakhya) on CodePen.

All the three div elements in the demo are given a width and height and overflow property set to auto (so that their contents become scrollable).

The first div is given background-attachment: scroll which made the background image fixed relative to the element, and thus it only moves on scrolling the element (and not its content).

Similarly, the second div is given the value local which made the background image fixed relative to element's content. So, it moves on scolling the scrollable content of the element.

The third div is given the value fixed which made the background image fixed relative to the viewport. So, the background image doesn't move.

## Giving different values for different background images

If an element has multiple background images, then giving one value to the background-attachment property will decide the scrolling behaviour of all the multiple backgrounds of that element. However, you can set different scrolling behaviours for different background images by giving multiple comma-separated values to the background-attachment property.

The first value specifies the scrolling behaviour of the first background image (towards the user), the second value for the second image, and so on.

HTML

<div></div>


CSS

div {
width: 300px;
height: 400px;
background-image: url('star.png'), url('tree.jpg');
background-attachment: scroll, fixed;
}


In the above example, the background-attachment property is given two comma-separated values. The first value scroll specifies the scrolling pattern for the first background image 'star.png', while the second value fixed for the second background image 'tree.jpg'.

Here's a demo for the same.

See the Pen background attachment values for different background images by Aakhya Singh (@aakhya) on CodePen.

## Browser Support

This property is supported in all modern browsers. Multiple background images are not supported in IE8 and earlier versions.

Liked the post?
Inquisitive and passionate Front-end Developer and Web Designer and Co-Founder of CodesDope.
Editor's Picks
0 COMMENT