html - 在绝对定位的 div 中固定背景

标签 html css

我试图在我的网站包装器的两侧实现两个固定的横幅。我使用绝对定位将横幅 div 附加到包装的每一侧,并在每个 div 中设置了固定背景,以便横幅跟随用户向下移动页面。

我似乎在设置横幅的背景位置时遇到问题,背景位置似乎与父 div 无关。我希望横幅背景在 div 中居中。

代码和示例 site

<style>
.page-container {
    position: relative;
    background: #FFF;
    width: 970px;
    margin-left:auto;
    margin-right: auto;
    background-color:#F00;
}

#left-bg {
    width: 306px;
    height: 100%;
    position:absolute;
    top: 0px;
    left: -306px;
    background:url(http://www.superfreeslotgames.com/basecamp/L-Leovegas-banner.gif);
    background-position: center center;
    background-attachment: fixed;
}

#right-bg {
    width: 306px;
    height: 100%;
    position:absolute;
    top: 0px;
    right: -306px;
    background:url(http://www.superfreeslotgames.com/basecamp/R-Leovegas-banner.gif);
    background-position: top center;
    background-attachment: fixed;
    background-position: center right;
}
</style>

<div class="page-container">  
  <div id="left-bg"></div>
  <div id="right-bg"></div>
</div> 

最佳答案

像这样更改您的 CSS:

.page-container {
    position: relative;
    background: #FFF;
    width: 970px;
    margin-left:auto;
    margin-right: auto;
    background-color:#F00;

    }

#left-bg {
    width: 306px;
    height: 100%;
    position:absolute;
    top: 0px;
    left: -306px;
    background:url(http://www.superfreeslotgames.com/basecamp/L-Leovegas-banner.gif) no-repeat 100% 0;
}

#right-bg {
    width: 306px;
    height: 100%;
    position:absolute;
    top: 0px;
    right: -305px;
    background:url(http://www.superfreeslotgames.com/basecamp/R-Leovegas-banner.gif) no-repeat 100% 0;
}

此外,除非您是故意这样做的,否则您应该考虑更改 right: -305px;(我也从您的专栏中更改了它,因为它在列)到 right:0

关于html - 在绝对定位的 div 中固定背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25587919/

相关文章:

javascript - postMessage 或 addEventListener 不起作用

javascript - Array.insert 函数错误作为 Object function Array() { [native code] } has no method 'insert'

html - 如何让 z-index 工作,它拒绝玩球

html - 如何从 HTML 页面中删除长水平滚动条

html - 这是 CSS 中的错误吗?

html - 盒子模型的问题

javascript - 如何使用纯 css 在悬停时放大图像?

php - mysql如何获取每一列的最大设置长度

css - 流体导航栏中图像的垂直居中

html - 使用 CSS 和 HTML 最大化网页上的图像