问题
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>
Now if I call it in my html like this:
<object type="image/svg+xml" data="hexagon-bg.svg" class="svg-hexagon"></object>
With this CSS:
.svg-hexagon
{
width: 10%;
min-width: 150px;
}
Its visible.
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");
}
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.
回答1:
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.
You'd need to convert the jpg file to a data URI if you want this to work.
来源:https://stackoverflow.com/questions/45476340/why-doesnt-this-svg-work-as-a-backgroud-image-in-css