HTML + CSS: fixed background image and body width/min-width (including fiddle)

Posted by insertusernamehere on Stack Overflow See other posts from Stack Overflow or by insertusernamehere
Published on 2012-06-27T10:01:24Z Indexed on 2012/06/28 15:16 UTC
Read the original article Hit count: 288

Filed under:
|
|
|

So, here is my problem. I'm kinda stuck at the moment.

I have a huge background image and content in the middle with those attributes:

  • content is centered with margin auto and has a fixed width
  • the content is related to the image (like the image is continued within the content)
  • this relation is only horizontally (vertically scrolling moves everything around)

This works actually fine (I'm only talking desktop, not mobile here :) ) with a position fixed on the huge background image.

The problem that occurs is the following: When I resize the window to "smaller than the content" the background image gets it width from the body instead of the viewport. So the relation between content and image gets lost.

Now I have this little JavaScript which does the trick, but this is of course some overhead I want to avoid:

$(window).resize(function(){

    img.css('left', (body.width() -  img.width()) / 2 );

});

This works with a fixed positioned image, but can get a litty jumpy while calculating.

I also tried things like that:

<div id="test" style="
    position:           absolute;
    z-index:            0;
    top:                0;
    left:               0;
    width:              100%:
    height:             100%;
    background:         transparent url(content/dummy/brand_backgroud_1600_1.jpg) no-repeat fixed center top;
"></div>

But this gets me back to my problem described.

Is there any "script-less", elegant solution for this problem?

UPDATE: now with Fiddle

The one I'm trying to solve:

http://jsfiddle.net/insertusernamehere/wPmrm/

The one with Javascript that works:

http://jsfiddle.net/insertusernamehere/j5E8z/

NOTE The image size is always fixed. The image never gets scaled by the browser. In the JavaScript example it get's blown. So don't care about the size.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about html