我发现了一个相当奇怪的问题,我想我知道如何解释;我只是不知道如何解决它!
我有一个div#container(一个div为100%min-height(IE的高度))的页面,包含一个 Headers ,一个"page-content"和一个页脚 . div#container的背景图像应该是固定的(不是固定位置,而是 background-attachment: fixed
,滚动时会使图片跟随) .
问题是,当固定附件添加到CSS中的background-tag时,背景图片现在位于div之外 .
CSS如下:(没有 background-attachment: fixed;
)
div#container {
position:relative;
width:900px;
margin:0 auto;
background-color: #ccffff;
background-image: url("pics/sign.jpg");
background-repeat: no-repeat;
background-position: right top;
height:auto !important;
height:100%;
min-height:100%;
}
margin:0 auto;
是以div为中心, height:
中的 !important
是使IE忽略该特定高度标记 . 如果 min-height: 100%
应该有效,这是必需的 .
当我添加这个...
div#container {
position:relative;
width:900px;
margin:0 auto;
background-color: #ccffff;
background-image: url("pics/sign.jpg");
background-attachment: fixed; //This is what is added to the code-sample
background-repeat: no-repeat;
background-position: right top;
height:auto !important;
height:100%;
min-height:100%;
}
......背景图片正在移动到div之外 . 让我解释一下:背景图像中唯一可见的部分仍然是 <div id="container">
内部,但是图像的一部分移动到了div之外,现在看不见了 .
总结一下......
当背景图像被修复时,背景图像被部分隐藏,移动到div之外 . 图像位于 browser window 的右上角,而不是div的右上角 .
希望你们能帮助我!
3 回答
这种行为实际上是正确的 . 任何
attachment: fixed
的背景都将相对于视口,而不是它应用的元素 . 这实际上是Eric Meyer的Complex Spiral演示的基础 .虽然div中没有固定的背景位置,但最简单的解决方案是创建一个与图像大小相同的div . 使图像成为背景,并使用
right:0px;top:0px
将其设置为要放置的div右上角的position:absolute
. 确保父div是position:relative
,否则它将不会完全位于该div中 .您应该尝试添加background-origin属性,也许
border-box
值将解决您的问题 . 您也可以定义background-size
,请记住cover
和contain
受支持且非常有用 .