background image position fixed to parent element
Asked Answered
G

3

7

I have a div somewhere on the page and I need to give it a background image that does not move when you scroll your browser window. This is my code so far:

#mydiv {
    float:left;
    width:540px;
    margin:40px 0px 0px 20px;
    background:url(/images/myimage.jpg) no-repeat fixed 0px 0px transparent;
}

The problem is that my background image is positioned relative to canvas and I need it to be positioned relative to #mydiv and still not scroll.

To illustrate the problem please see here http://jsfiddle.net/QPrUz/1/
In the example #div1 looks fine but #div2 does not show the background at all as it is positioned relative to the canvas instead of #div2.

Any suggestions are welcome.

P.S.
iframe is not an option.

Gauffer answered 12/6, 2011 at 17:6 Comment(1)
If the background-image has been placed using a fixed background-attachment value, the background-position refers to the viewport, rather than the element’s padding box. - reference.sitepoint.com/css/background-positionIrrawaddy
G
5

As per Jawad's comment it's not possible using CSS. I ended up changing a background to something repeatable.

Gauffer answered 28/7, 2011 at 10:29 Comment(0)
M
0

MDN for fixed says:

This keyword means that the background is fixed with regard to the viewport.

Use scroll instead of fixed:

This keyword means that the background is fixed with regard to the element itself and does not scroll with its contents. (It is effectively attached to the element's border.)

So, the full code for sticky background fixed relative to the element itself:

.sticky-background {
    background: url(...) no-repeat scroll;
}
Mount answered 10/8, 2015 at 8:5 Comment(0)
C
0

If I understood the question, you just have to position the top/left of the background image so that div2 looks like div1.

here it is: http://jsfiddle.net/7kku4v1t/

I only changed:

background:url(http://i35.tinypic.com/4tlkci.jpg) fixed no-repeat;

to

background:url(http://i35.tinypic.com/4tlkci.jpg) 210px 0 fixed no-repeat;
                                                  ^^^^^^^
                                                  X     Y
Cavalcade answered 29/8, 2017 at 20:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.