开发者

Technique for using a wide background div without affecting body width

Please reference this example with the following explanation:

I have a web page with an extra-wide, centered background image. I want the body width of the page to collapse to the content, and ignore the div that contains the background. In the given example, I have a simplified example of how I do this: An bg-out开发者_Python百科er div establishes the proper page width (200px wide), and an bg-inner div (400px wide) contains the extra-wide image. I then use overflow:visible and negative margins to attempt to center the wider bg-inner without increasing the page width. However, as the example shows, horizontal scrollbars appear when the browser window is less than 400px, not 200px. Why does this happen? Is there a better approach?

Thanks-

EDIT:

Here's a duplicate I ended up finding, with a similiar though slightly different solution. I like the answer wdm gives here better though.


Duplicate post: Why do negative margins affect my page width?

However this one explains better what you're trying to accomplish.

This is simple...

Demo: http://jsfiddle.net/wdm954/L3U9c/

<div id="bg">
    <div id="content">
        Here is my content.
    </div>
</div>


#bg {
    background-color: red;
    background-position: top center; /* for images */
}
#content {   
    margin-left: auto;
    margin-right: auto;
    position: relative;
    left: 0px;
    top: 0px;
    width: 200px;
    background-color: #ccc;
}


You can add

body {
    overflow-x: hidden;
}


I think all you need for what you're doing is 3 lines of CSS:

body {
    background-image:url('myurl.jpg');
    background-position:center;
    background-size:cover;
}

As you can see:

<body>
    <p>This is my document. Nothing else necessary</p>
    <!-- any other content you desire -->
</body>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜