没有浏览器滚动的Div比浏览器更宽

问题描述:

我正在处理主内容div将具有970px的布局。这个div后面,我想与尺寸位置,像这样一个div 1200x600px(它将包含Flash对象):没有浏览器滚动的Div比浏览器更宽

width:1200px; 
height:600px; 
position:absolute; 
left:50%; 
margin-left:-600px; 

当浏览器尺寸小于1200像素小的宽度得到它的水平滚动条的问题是。我可以解决这个问题通过:

body {overflow-x:hidden;} 

但我不希望它有水平滚动条时,得到尺寸小于970像素宽。

基本上,我试图让1200px div行为更像一个CSS背景图像。有任何想法吗?

这工作没有JavaScript:

<body style="margin:0"> 
<div style="position:absolute;width:100%;height:600px;overflow:hidden;min-width:970px;z-index:0;"> 
<div style="position:absolute;width:1200px;height:600px;left:50%;margin-left:-600px;"> 
    --flash object-- 
</div> 
</div> 
<div style="position:absolute;width:100%;z-index:100;"> 
--main content-- 
</div> 
</body> 

UPDATE:不得不作出改变,以适应您的绝对DIV定位(父div有要绝对定位)

+0

这会将这些框放在两个维度的正确位置,但它将内容放在背景之后。 – danorton 2010-09-05 00:49:22

+0

@danorton使用CSS属性z-index将您的主体设置在顶部。我会更新我的上述代码。 – userx 2010-09-05 01:47:53

+0

真棒解决方法!不错的工作! – spez86 2012-04-09 22:25:31

您可以使用onresize事件,当其小于970px时,将overflow-x更改为自动或滚动。

如果你正在使用jQuery,仰望.resize()方法

+1

如果你打算这样做,确保你使用dobouncing:http://benalman.com/code/projects/jquery-dotimeout/examples/debouncing/(检查第二个例子) – 2010-09-04 21:05:09

+0

debouncing看起来非常有用,本阿曼写了一些整洁的插件。我最近使用他的haschange和烧烤插件。 – 2010-09-04 21:10:28

一个解决方案完全可以使用CSS。关键件是位置:固定z-index:-1。这个例子中的两个DIV是兄弟姐妹,但还有其他的可能性。该解决方案适用于最新版本的Chrome,FireFox,Safari,Opera和MSIE。

这不会MSIE6,不正确执行的z-index的工作作风,但有一个MSIE6兼容的解决方案(这表明在1200像素的滚动条),如果你能重新安排事物,添加一个DIV包装器。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html title="html"> 
    <head> 
    <style type="text/css"> 
    #content 
    { 
     background: #ffffe8; 
     height: 500px; 
     margin: 0 auto; 
     width: 970px; 
    } 
    #background 
    { 
     background: #ffe8e8; 
     height: 600px; 
     left: 50%; 
     margin-left: -600px; 
     position: fixed; 
     top: 0; 
     width: 1200px; 
     z-index: -1; 
    } 
    </style> 
    </head> 
    <body title="body"> 
    <div id="content" title="#content"> 
     <p>content</p> 
    </div> 
    <div id="background" title="#background"> 
     <p>background</p> 
    </div> 
    </body> 
</html> 

我会使用CSS3媒体查询。

body{overflow:hidden;} 

@media only screen and (max-width: 970px) { 
    body{overflow:visible;} 
} 

首先设置要隐藏的身体溢出,以便它不滚动。然后当屏幕小于970像素时,将其设置回可见状态,以便滚动。