Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix background image inside div

I've discovered a rather odd problem, which I think I know how to explain; i just don't know how to fix it!

I have a page with a div#container (a div with 100% min-height (height for IE)) containing a header, a "page-content" and a footer. The background image of the div#container is supposed to be fixed (not fixed position but background-attachment: fixed which makes the picture follow when you scroll).

The problem is, that when fixed attachment is added to the background-tag in CSS, the background picture is now positioned outside the div.

The CSS is as follows: (without background-attachment: fixed;)

div#container {
    position:relative;
    width:900px;
    margin:0 auto;
    background-color: #ccffff;
    background-image: url("pics/sign.jpg");
    background-repeat: no-repeat;
    background-position: right top;

    height:auto !important;
    height:100%;

    min-height:100%;
}

margin:0 auto; is to center the div and the !important thing in the first height: is to make IE ignore that particular height-tag. This is required if min-height: 100% should work.

When I add this...

div#container {
    position:relative;
    width:900px;
    margin:0 auto;
    background-color: #ccffff;
    background-image: url("pics/sign.jpg");
    background-attachment: fixed; //This is what is added to the code-sample
    background-repeat: no-repeat;
    background-position: right top;

    height:auto !important;
    height:100%;

    min-height:100%;
}

...the background picture is moving outside of the div. Let me explain this: The only visible part of the background image is what is still inside the <div id="container"> but a part of the image has moved outside the div and is now invisible.

To sum up...

When the background image is fixed, the background image is partly hidden, moving outside the div. The image is positioning to the top right of the browser window, not to the top right of the div.

Hope you guys can help me!

like image 272
Latze Avatar asked Aug 20 '10 20:08

Latze


2 Answers

This behavior is actually correct. Any background which is attachment: fixed will be relative to the viewport, not the element it is applied to. This is actually the basis of Eric Meyer's Complex Spiral demo.

like image 194
Ryan Kinal Avatar answered Sep 25 '22 18:09

Ryan Kinal


While you cannot have a fixed background position within a div, the easiest solution would be to create a div the size of your image. Make the image the background, and set it to position:absolute in the top right corner of the div you want it placed in using right:0px;top:0px. Be sure that the parent div is position:relative or it won't be positioned absolutely within that div.

like image 42
Matt Healey Avatar answered Sep 23 '22 18:09

Matt Healey