Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG in CSS backgrounds not showing up in Safari

Tags:

html

css

safari

svg

The following code doesn't work in Safari, and the image doesn't show up. This only happens in Safari, it works in all other browsers, I can't figure out why. Here is the CSS code:

.hero {
        background: url(images/cards.svg) no-repeat center center fixed;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        background-size: cover;
        height:180px;
        width:100%;
        margin-bottom:20px;
    }

and the HTML code:

<div class="hero"></div>

Update: The above code works when converting the "cards.svg" into a JPG, but I would rather work with SVG as they load faster. Why would the SVG not show up in Safari (7.0.1)? According to http://caniuse.com, SVG as a CSS background image is supported but it won't display.

like image 266
Tim Avatar asked Mar 16 '14 02:03

Tim


People also ask

Does SVG have background?

The SVG stands for Scalable Vector Graphics. The SVG background is used to draw any kind of shape, set any color you want by the set property.

Can I use SVG as background-image CSS?

SVG images can be used as background-image in CSS as well, just like PNG, JPG, or GIF. All the same awesomeness of SVG comes along for the ride, like flexibility while retaining sharpness. Plus you can do anything a raster graphic can do, like repeat.

Can we add SVG in CSS?

We can use SVG in CSS via data URI, but without encoding it works only in Webkit based browsers. If encode SVG using encodeURIComponent() it will work everywhere. SVG must have attribute xmlns like this: xmlns='http: //www.w3.org/2000/svg' . If it doesn't exist, it will be added automagically.

Why is my background not showing up CSS?

Make sure the image path is set correctly in the background-image url. Once you have made sure that your CSS file is linked correctly, also check that the image itself is set correctly. Again, you will want to open your code inspector in the browser to check.


2 Answers

It's because my server is serving it with an incorrect content-type.

Had to add this to my .htaccess file:

AddType image/svg+xml .svg .svgz

This helped me out: http://css-tricks.com/snippets/htaccess/serve-svg-correct-content-type/

like image 119
Tim Avatar answered Oct 07 '22 17:10

Tim


I ran into the same problem, although in my case it wasn't the content type that was the problem. It turned out that I had to add quotes around the URL to get it to work, i.e.:

background-image: url('/path/to/my.svg');

...not:

background-image: url(/path/to/my.svg);

I know this isn't the issue the OP was encountering, but posting this here for the benefit of anyone else who runs into the same issue as me and comes to this thread.

like image 39
UnknownDeveloper Avatar answered Oct 07 '22 18:10

UnknownDeveloper