回答你的第一个问题:
Put the background-image
on a 伪元素 ::before
反而:
#InnerImage::before {
background: url('imgurl.com') no-repeat center left;
content: "";
position: absolute;
/* the following makes the pseudo element stretch to all sides of host element */
top: 0; right: 0; bottom: 0; left: 0;
z-index: 1;
}
这需要设置position: relative;
on #InnerImage
:
#InnerImage {
position: relative;
}
并且您需要使用以下命令确保所有其他子元素都位于伪元素之上z-index
(这仅适用于您定位这些元素时所需的方式):
#InnerImage * {
position: relative;
z-index: 2;
}
Notice: #OuterImage #InnerImage
可以安全地缩短为#InnerImage
因为一页上可能只有一个元素具有任何给定的id
无论如何有价值。另外我建议不要使用id
CSS 中的选择器除非你明确知道你为什么这样做.
关于您的动画,似乎您希望它仅在两秒过去后才开始。这可以通过使用transition
像这样:
transition: opacity 1s ease 2s;
where 1s
is transition-duration
and 2s
is transition-delay
.
https://developer.mozilla.org/en/docs/Web/CSS/transition
Example:
#InnerImage::before {
background: url(http://lorempixel.com/300/200) no-repeat center left;
content: "";
position: absolute;
/* the following makes the pseudo element stretch to all sides of host element */
top: 0;
right: 0;
bottom: 0;
left: 0;
transition: opacity 1s ease 2s;
z-index: 1;
}
#InnerImage {
position: relative;
width: 300px;
height: 200px;
}
#InnerImage * {
position: relative;
z-index: 2;
}
#InnerImage:hover::before {
opacity: 0.25;
}
<div id="InnerImage">
<h2>Hey!</h2>
<button>noop</button>
</div>
如果你想要永久持续的淡入淡出,你必须使用动画片代替过渡.
#InnerImage::before {
background: url(http://lorempixel.com/300/200) no-repeat center left;
content: "";
position: absolute;
/* the following makes the pseudo element stretch to all sides of host element */
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1;
animation: 3s ease 0s normal forwards 1 fadein;
animation-iteration-count: infinite;
}
#InnerImage {
position: relative;
width: 300px;
height: 200px;
}
#InnerImage * {
position: relative;
z-index: 2;
}
@keyframes fadein{
0% { opacity:0; }
50% { opacity: 1; }
100% { opacity:0; }
}
<div id="InnerImage">
<h2>Hey!</h2>
<button>noop</button>
</div>