如何使背景图像比网站的内容区域更宽(没有滚动条)

时间:2009-12-24 09:39:54

标签: html css background scrollbar overflow

我已经获得了一个网站的设计,我正在尝试实现它。

我遇到的一个问题是该设计有一些背景图像(一个用于标题,一个用于正文,一个用于网站的页脚),它们比网站的主要内容区域更宽。

简单地将它们作为背景图像放置不起作用,因为如果浏览器窗口不够大,无法完全显示背景,则扩展标题,正文和页脚div足以容纳背景会导致出现水平滚动条。

这是不受欢迎的,因为背景对于浏览网站并不重要,我不希望它们出现滚动条(只有在浏览器太小而无法完全显示网站内容时才会出现滚动条)。

第二种方法是使用一个单独的,绝对定位的div来显示标题背景图像(并将其放在具有浏览器窗口大小的元素下),并将其宽度设置为100%,以便它永远不会超过浏览器窗口(因此创建滚动条)。

这可以解决问题 - 然而,当窗口太小时,背景开始相对于内容移动,因为背景的“顶部中心”位置相对于浏览器窗口,而不是内容区域。在大尺寸下,由于内容区域居中,因此这些实际上是相同的,但是在小尺寸时,仅显示部分内容,因此内容的中心和浏览器窗口的中心是不同的。

我发现这个问题的一个很好的例子是Quicken网站:http://quicken.intuit.com/。在大尺寸下,它的云背景看起来很好,但是如果你让窗户的宽度足够小,那么云就会相对于内容开始移动(糟糕!)。

有关如何修复此问题的任何想法,以便背景图像

  1. 不要创建滚动条,因为它们不是网站内容的一部分
  2. 相对于网站内容是固定的(并且不会在较小的浏览器窗口大小处移动)
  3. 理想的解决方案就是将溢出转换为隐藏在身体上,但仅限于指定的div。不幸的是,我相信这是不可能的。

    我更喜欢纯粹的html / css解决方案,但我接受我可能需要js来获得我想要的效果。

    谢谢! (这是一个复杂的问题,所以如果需要澄清,请告诉我)

    更新:通过将背景div上的min-width设置为内容的宽度来解决此问题。

5 个答案:

答案 0 :(得分:4)

您需要拥有标题,内容和广告。页脚宽度为100%。并将图像作为背景图像放入这些div中......水平居中。

特定div内部有一个居中的包装器。并且是divs内容的宽度。

喜欢这样。

HTML

<div id="header">
    <div class="wrapper">
        ...
    </div>
</div>
<div id="content">
    <div class="wrapper">
        ...
    </div>
</div>
<div id="footer">
    <div class="wrapper">
        ...
    </div>
</div>

CSS

div#header {
    background: url(...) 50% 0; /* to center your background image horizontally */
    }

div#content {
    background: url(...) 50% 0; /* to center your background image horizontally */
    }

div#footer {
    background: url(...) 50% 0; /* to center your background image horizontally */
    }

div.wrapper {
    margin: 0 auto; /* to center the div horizontally */
    width: 960px; /* or however wide it should be */
    }

希望这有帮助。

答案 1 :(得分:4)

将包含背景图像的div的最小宽度设置为内容的宽度。

答案 2 :(得分:0)

我错过了什么,或者您是否应该使用CSS background-image属性?

我看了一下Quicken网站,说实话,当浏览器调整大小时云背景图像的移动不应该担心,除非你的背景图像最明显而不是一堆云。

明白我的意思?

答案 3 :(得分:0)

您可以使用overflow属性并将其设置为隐藏在div上,导致滚动条出现。

答案 4 :(得分:0)

我在我工作的网站上遇到了同样的问题,并提出了以下解决方案,如果所有背景图片的宽度都相同,则效果很好。

/* 
A container div that is set to the 100% width, with the overflow set to hidden. 
This hides the overflowing images if the window sizes is too small 
*/

#bg_container {
    position:absolute;
    z-index:0;
    top:0px;
    width:100%;
    overflow:hidden;
}

/* 
A div that sets the size of the content and centers itself on the page. 
*/

.bg {
    margin:0 auto;
    width:1000px;  /* content size */
    overflow:visible;
}

/* 
Here I set the image away from the left edge of the div to center it to the content. The actual size of the image is 1500px. 
*/

.bg img {
    margin-left:-250px;
}