CSS 的 CRT 效果为什么没有显示在 <img> 上?
数据小陈
结论
问题出在把 ::before 和 ::after 直接挂在 <img> 上,跟用 class 还是 id 没关系。<img> 是替换元素,浏览器通常不会给它生成伪元素;就算个别浏览器能显示,也不该依赖这个行为。还有一个问题:伪元素用了 position: fixed,它覆盖的是视口,不是图片本身。
为什么只影响 div/span
伪元素可以理解成宿主元素内部生成的盒子。宿主是普通 div 时,效果会落在整个容器上;<img> 不能包含子节点,所以效果不会出现在图片内部。把 class 改成 id 也一样,规则不变。
改法
给图片外面套一个容器,让容器来承载伪元素,同时用 position: relative 给它建立定位参照。伪元素改为 position: absolute; inset: 0;,这样就会覆盖图片区域。容器尺寸由图片决定。示例:
<div class='crt'>
<img src='http://placekittens.com/400/200' alt=''>
</div>
body {
margin: 0;
}
.crt {
position: relative;
display: inline-block;
overflow: hidden;
}
.crt img {
display: block;
width: 75%;
}
.crt::before {
content: '';
position: absolute;
inset: 0;
background: linear-gradient(rgba(18, 16, 16, 0) 50%, rgba(0, 0, 0, 0.25) 50%), linear-gradient(90deg, rgba(255, 0, 0, 0.06), rgba(0, 255, 0, 0.02), rgba(0, 0, 255, 0.06));
background-size: 100% 2px, 3px 100%;
z-index: 2;
pointer-events: none;
}
.crt::after {
content: '';
position: absolute;
inset: 0;
background: rgba(18, 16, 16, 0.1);
opacity: 0;
z-index: 2;
pointer-events: none;
animation: flicker 0.15s infinite;
}
@keyframes flicker {
0% { opacity: 0.27861; }
5% { opacity: 0.34769; }
10% { opacity: 0.23604; }
15% { opacity: 0.10626; }
20% { opacity: 0.18128; }
25% { opacity: 0.10626; }
30% { opacity: 0.18128; }
35% { opacity: 0.23604; }
}
上面的 inset: 0 覆盖的是 .crt 的 padding box。如果 .crt 比图片大,需要让容器宽度和图片一致,或者把 width: 75% 放到 .crt 上,让 img 使用 width: 100%。
如果你想要全屏扫描线
如果要做全屏扫描线,就让伪元素继续保持 position: fixed,但挂到 body::before、body::after 或单独的 overlay 元素上,不要挂在 <img> 上。否则 fixed 伪元素会覆盖整个视口,跟图片尺寸没有关系。
其他排查点
- 用
body { margin: 0; }代替topmargin、leftmargin这类旧属性。 - 除非确实想裁切,不然不要让父元素的
overflow: hidden把伪元素需要定位的部分裁掉。 - 页面祖先元素上如果有 transform、filter 或 opacity,fixed/absolute 和 z-index 的堆叠上下文会跟着变化。
备注:内容仅供参考。
