澄清一下,我不是在问 stacking background images在一个 HTML 元素内。
相反,我有一个网站,其最外面的 div 上有一个背景图像,它是网站设计的一个组成部分。该网站的开发目的是无需滚动即可填充浏览器窗口。
但是,在某些具有较长文本内容的页面上,有较小的、固定高度的窗口允许滚动。
我正在尝试实现 fade-out bottom CSS trick ,这样文本在滚动到 View 中时就会成为焦点。这需要另一个背景图像。
淡出底部效果所需的渐变背景图像会干扰网站主体的背景图像。正如您在我的 fiddle 中看到的那样,它会产生“删除”背景图像部分的效果。
z-index
属性在这里似乎没有做任何事情,我似乎无法找到调整这些不同背景图像的堆叠的方法。理想情况下,我希望主背景图像覆盖渐变背景图像。
.main-content {
position: relative;
width: 100%;
height: 800px;
background: #fff url(https://s-media-cache-ak0.pinimg.com/originals/1c/86/08/1c86080e8526b769bda7446582f72f76.png) no-repeat;
background-size: cover;
z-index: 1;
}
.text-section {
position: relative;
width: 50%;
margin: 0 auto;
height: 400px;
color: #0077c0;
font-size: 14px;
font-weight: bold;
border: 1px solid green;
}
.text-section p {
position: absolute;
bottom: 0;
}
.gradient {
width: 100%;
background: url(https://css-tricks.com/examples/FadeOutBottom/bottom-fade.png);
height: 200px;
width: 100%;
position: absolute;
bottom: 0;
z-index: 0;
}
<div class="main-content">
<div class="text-section">
<p>
Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas
</p>
<div class="gradient"></div>
</div>
</div>
最佳答案
我的问题的解决方案有点棘手,但我最终用纯 CSS 完成了我的特定案例所需的内容。首先,我给我的主要内容包装器一个带有透明覆盖层 .png 的伪元素(字母除外):
关键是 pointer-events
css 属性。这允许用户点击覆盖层而不与其交互。此属性得到了相当广泛的支持(即使在 IE11 中也是如此;但不支持 IE10 或更低版本)。
然后,您只需确保主要内容包装器和所有子元素的 z-index
属性设置为“auto”,除非您确实希望覆盖特定元素梯度,在这种情况下,您可以为该元素指定一个正值。
虽然这个解决方案看起来有点奇怪,但它非常适合我的实际设计(字体不是完全不透明,所以它似乎淡入背景,而不会被模糊渐变切断。当然,有,字母也更少。
希望这对遇到类似问题的人有所帮助。
.main-content:after {
position: absolute;
content: "";
top: 0;
left: 0;
bottom: -270px;
right: 0;
pointer-events: none;
background-size: 100% 800px;
overflow: hidden;
background: url(https://s-media-cache-ak0.pinimg.com/originals/1c/86/08/1c86080e8526b769bda7446582f72f76.png) no-repeat bottom left;
}
.text-section {
position: relative;
width: 50%;
margin: 0 auto;
height: 400px;
color: #0077c0;
font-size: 14px;
font-weight: bold;
border: 1px solid green;
}
.text-section p {
position: absolute;
bottom: 0;
}
.gradient {
width: 100%;
background: url(https://css-tricks.com/examples/FadeOutBottom/bottom-fade.png);
height: 200px;
width: 100%;
position: absolute;
bottom: 0;
}
<div class="main-content">
<div class="text-section">
<p>
Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas
</p>
<div class="gradient"></div>
</div>
</div>
关于javascript - 如何调整来自不同 HTML 元素的背景图像的堆叠顺序/z-index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45088376/