CSS background-attachment

The background-attachment CSS property allows fixing the background of an element so that it doesn't scroll with the rest of the page, as seen in Twitter. It's normally used to fix the background of the html or body elements, as seen in Twitter.

background-attachment: fixed|local|scroll
background-attachment: fixed;   /* fix to the body */

Note that the fixed value fixes the background with respect to the body element always. The background may appear misaligned when the property is applied to any other element. The background-position is then relative to the top left corner of the body. There's no way to position the background with respect to the element's initial edge.

Browser Support: Full.

Fixing the Background

The background-attachment: fixed rule will fix the background to the viewport. The element scrolls but the background remains fixed.

div.box{
background-image: url('http://codeitdown.com/images/stripes.jpg'); background-attachment: fixed;
}

fixed backgrounds are more common in the body element. It looks quite different from the example because the whole content of the page scrolls down.

Scroll the Background with background-attachment: local

local is probably not as famous a value as fixed. It is meant for elements with scrollbars. The background of a scrollable element doesn't scroll by default. local attaches the background to the content of the element so that it scrolls as well.

div.scrollable{
background-image: url('http://codeitdown.com/images/wood.jpg'); background-attachment: local; overflow-y: scroll;
}

background is shorthand

The background property allows setting all the background related properties at the same time.

 background: color position size repeat origin clip attachment;

To fix a repeating background use, use the following:

div.body {
	background: green url('path_to_image') fixed;
}

Always provide a background color to show if the image is not loaded.

Add no-repeat for a single non-repeating instance of the background image. Keep in mind that it will be positioned with respect to body always.

Full Page Background

A fixed background is not enough for a full page background where you want the background size to scale with the viewport. The CSS3 background-size property will help here. The following rules will scale the image as small as possible as long as both of its dimensions are larger than or equal to the background area of the element/viewport.

html { 
	background: cover fixed url('path_to_image');
}

Source: Perfect Full Page Background Image - CSS-Tricks

Useful Resources

Leave a Reply

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>