为什么此svg不能在CSS中用作背景图像? [英] Why doesnt this svg work as a backgroud image in css?

查看:110
本文介绍了为什么此svg不能在CSS中用作背景图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用illustrator并通过阅读裁剪以适合svg模式制作了.svg :

I made this .svg using illustrator and from reading Crop to fit an svg pattern:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 149 172">
    <defs>
      <pattern id="img" width="1" height="1" patternContentUnits = "objectBoundingBox" viewBox="0 0 1 1" preserveAspectRatio="xMidYMid slice">
        <image xlink:href="https://c1.staticflickr.com/7/6037/6254709876_af26f8425b_b.jpg" preserveAspectRatio = "xMidYMid slice"  width = "1" height = "1" />
      </pattern>
    </defs>
    <polygon  points="0.5 128.75 0.5 43.3 74.5 0.58 148.5 43.3 148.5 128.75 74.5 171.47 0.5 128.75" fill="url(#img)"></polygon>
</svg>

现在,如果我在html中这样调用它:

Now if I call it in my html like this:

<object type="image/svg+xml" data="hexagon-bg.svg" class="svg-hexagon"></object>

使用此CSS:

.svg-hexagon
{
    width: 10%;
    min-width: 150px;
}

可见.

但是,如果我使用此CSS将.svg设置为背景图片:

However if I set the .svg as a background image using this CSS:

.svg-hexagon-bg
{
    width: 200px;
    height: 200px;
    background-size: cover;
    background-position: center center;
    background-image: url("hexagon-bg.svg");
}

然后像这样在我的html中调用它:

and then call it in my html like this:

<div class="svg-hexagon-bg"></div>

它是不可见的.有人知道为什么吗.我想将其显示为背景图像,因此以不同的分辨率将其更改为正方形.

It is not visible. Does anyone know why this is. I want to display it as a background image so at a different resolution I change it to a square.

推荐答案

如果您将SVG用作背景图片(或其他任何图片上下文,例如通过img文件),则该图片必须是自包含的,即不能具有任何外部引用,例如外部CSS文件或本例中的外部jpg文件.

If you use an SVG as a background image (or any other image context such as via an img file), it must be self contained i.e. it can't have any external references such as external CSS files or in this case external jpg files.

如果您需要将jpg文件转换为数据URI 希望它能正常工作.

You'd need to convert the jpg file to a data URI if you want this to work.

这篇关于为什么此svg不能在CSS中用作背景图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆