Get Off My Lawn
Get Off My Lawn

Reputation: 36289

SVG background image isn't displaying

I am trying to add an SVG as a background image, and for some reason it isn't displaying, and I am not sure why.

Here is the svg:

<svg viewBox="0 0 1000 100" preserveAspectRatio="none">
    <polygon points="0,0 1000,0 1000,50 0,50" style="fill:#01b6ef;" />
    <polygon points="0,0 500,0 0,100" style="fill:#222c37;" />
</svg>

Here is the CSS:

.head-nav{
    background-image: url("/media/images/header.svg");
    background-repeat: no-repeat;
    height: 100px;
}

And here is the HTML (with css bootstrap):

<div class="fluid-container head-nav"></div>

When I look at the headers in chrome they look like this (I am also getting a 200 back):

Accept-Ranges:bytes
Connection:keep-alive
Content-Length:196
Content-Type:image/svg+xml
Date:Sun, 14 Dec 2014 15:46:10 GMT
ETag:"548daee8-c4"
Last-Modified:Sun, 14 Dec 2014 15:38:16 GMT
Server:nginx/1.4.6 (Ubuntu)

When I place the xml directly in the html the image displays, but not as a background image. Any suggestions?

Upvotes: 1

Views: 7141

Answers (2)

Robert Longson
Robert Longson

Reputation: 123985

When you have a standalone SVG file served as image/svg+xml it must have the correct namespaces or it won't be displayed. html doesn't have namespaces which is why it works if you embed the SVG data directly in an html file.

So your SVG file needs to look like this...

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 100" preserveAspectRatio="none">
    <polygon points="0,0 1000,0 1000,50 0,50" style="fill:#01b6ef;" />
    <polygon points="0,0 500,0 0,100" style="fill:#222c37;" />
</svg>

If you had tried to display the standalone file directly, the UA should have given you some kind of helpful message.

Upvotes: 5

Patrick
Patrick

Reputation: 882

Try adding background-size:contain; to your .head-nav class. SVG as a background needs to have the background size in order to show the full image.

By using background-size:contain; instead of a specific height and width, it becomes device agnostic.

Hopefully that will work for you.

Upvotes: 2

Related Questions