insertusernamehere
insertusernamehere

Reputation: 23580

Fixed background image horizontally connected to content with fixed width

The problem is: I have a huge background image and content with those characteristics:

This works fine, actually, on desktop devices with position fixed on the background image.

But the problem is: When I resize the window until it's smaller than the content, the content is fixed on the left side, but the background image is still centered, as expected. In this case the connection between both elements gets lost.

I have this JavaScript that does the trick, but this is of course some overhead I want to avoid as it isn't smooth anytime due to the calculation:

$(window).resize(function(){
    container.css('left', (body.width() - img.width()) / 2);
});

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(path) no-repeat fixed center top;
"></div>

But this results in the same issue described above.

Is there any elegant CSS solution for this problem?

Demo

Try it yourself

NOTE

The image size is fixed and known and it never gets scaled by the browser.

Upvotes: 3

Views: 3930

Answers (1)

Seimen
Seimen

Reputation: 7250

Is this working for you? http://jsfiddle.net/wPmrm/24/

HTML

<div class="background">
<div class="content">
    CONTENT
    <br><br>
    This example works fine until you the viewport size gets smaller than this content. After that the image isn't sticky anymore.
    <br><br>
    And check out vertical scrolling.

    <div style="height:1500px;"></div>
    END
</div>
</div>

CSS

div.background {
    min-width: 740px;
    background: url('http://placehold.it/1600x1050') top center fixed no-repeat;
}

div.content {
    width: 700px;
    height: 2000px;
    margin: auto;
    padding: 50px 20px;
    background: none;
    opacity: 0.7;
    color: #333;
}

.background should be the wrapper for .content with a centered background and have a minimum-width of the .contents width+padding.

Update from comments:

http://jsfiddle.net/wPmrm/28/

We'll have to use a media-query, so when the width is at max 740px we change the background position. Oh and we set background-attachment to fixed again.

CSS added

@media screen and (max-width:740px) {
    div.background {
        background-position: -435px 0;
    }
}

I don't see why it is -435px ((1600-740)/2 would be 430) but it seems to be the most accurate value.

Upvotes: 1

Related Questions