使用宽背景div而不影响主体宽度的技术 [英] Technique for using a wide background div without affecting body width

查看:115
本文介绍了使用宽背景div而不影响主体宽度的技术的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参考以下说明示例



我有一个网页,有一个超宽的,居中的背景图片。我想要页面的主体宽度折叠到内容,并忽略包含背景的div。在给定的示例中,我有一个简单的例子,我如何做到:bg-outer div建立适当的页面宽度(200px宽),bg-inner div(400px宽)包含超宽的图像。然后我使用溢出:可见和负边距尝试中心更宽的bg-inner而不增加页面宽度。但是,如示例所示,当浏览器窗口小于400像素而不是200像素时,会出现水平滚动条。为什么会发生?是否有更好的方法?



感谢 -



编辑: >

以下是重复我最终找到了一个类似但略有不同的解决方案。我喜欢这里的答案wdm在这里更好。

解决方案

重复的帖子:为什么负边距会影响我的网页宽度?





这是很简单的...



演示: http://jsfiddle.net/wdm954/L3U9c/

 < div id =bg> 
< div id =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;
}


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-outer 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;
}

这篇关于使用宽背景div而不影响主体宽度的技术的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆