css - 图片下方的 SVG 背景

标签 css image svg background

所以我想做的是在鼠标悬停时在图像上叠加 SVG。最终我会为它制作动画,但现在我只是想让叠加层正常工作。这是我尝试过的:

<div class="centering margin-on-top">
   <img id="img1" src="media/circle-1.jpg" />
   <img id="img2" src="media/circle-2.jpg" />
   <img id="img3" src="media/circle-3.jpg" />
</div>

CSS:

#img1:hover {
    background: url("../svg/stroke-ears.svg") no-repeat;
}

起初我以为它根本不起作用。但是当我将鼠标悬停在包含的 div 上并删除“检查元素”窗口内的图片时,svg 在那里但隐藏在图像下方。

有没有办法在图像或背景上设置 z-index?

提前致谢。

最佳答案

将您的 CSS 更改为:

#img1 {
    position: relative;
}
#img1:hover:after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url("../svg/stroke-ears.svg") no-repeat;
}

您正在做的是创建一个伪元素以覆盖在 img 之上。您的原始 img 将背景应用于 img 的背景,而不是覆盖它。

这个新的解决方案在普通 DOM 之外创建了一个元素,它将把您的 img 视为一个容器,并用一个具有您想要应用的原始背景的元素覆盖其整个尺寸。

更新

JSFiddle example

所以,愚蠢的我,试图将 img 视为包含元素。这是修复。

HTML

<div class="inline-container centering margin-on-top">
    <div class='img-holder'>
        <img id="img1" src="http://placehold.it/200x200" />
    </div>
    <div class='img-holder'>
        <img id="img2" src="http://placehold.it/200x200/FBC93D" />
    </div>
    <div class='img-holder'>
        <img id="img3" src="http://placehold.it/200x200/075883" />
    </div>
</div>

CSS

.inline-container {
    font-size: 0;
}
.img-holder {
    position: relative;
    display: inline-block;
}
.img-holder:hover:after {
    content: '';
    position: absolute;
    top: 0; bottom: 0; right: 0; left: 0;
    background: url("http://placeskull.com/200/200") no-repeat;
}

如果您想缩短 HTML,您也可以轻松地将图像交换为新 div 上的背景图像。

关于css - 图片下方的 SVG 背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29146874/

相关文章:

html - 构建圆形百分比图表

html - Svg defs 封装

svg - SVG 中的混合模式

javascript - 如何让div跟随鼠标?

javascript - 在 React 中单击按钮时使文本淡入/淡出

android - 删除图片后如何刷新Recyclerview?

cmd - 如何使用 wget 从域下载所有图像

html - 纯 CSS 两列布局

css - AMP 和太宽的表格

java - 无法从 Jar 加载图像