【问题标题】:SVG background underneath image图像下方的 SVG 背景
【发布时间】:2015-05-22 16:51:05
【问题描述】:

所以我想做的是在悬停时在图像上叠加一个 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 image svg background


    【解决方案1】:

    将您的 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

    所以,愚蠢的我,试图将imgs 视为包含元素。这是解决方法。

    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 上的背景图像。

    【讨论】:

    • 什么都没发生。然而,现在当我在检查元素窗口中应用 :hover 选择器时,CSS 规则不会出现。猜测是因为 :after.
    • 太棒了!叠加效果很好! :D 唯一的问题是,我认为绝对定位会与页面上的其他 css 混淆。图像现在在其下方的元素下方滑动。已尝试添加边距、填充等。
    • 尝试将z-index: 1 添加到包含图像的divs 的CSS 中。
    猜你喜欢
    • 2017-10-06
    • 1970-01-01
    • 2017-01-18
    • 2014-03-24
    • 1970-01-01
    • 2011-09-11
    • 2016-02-12
    • 2019-01-28
    • 1970-01-01
    相关资源
    最近更新 更多