Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG as a CSS background

Tags:

html

css

svg

I've been trying to get a simple SVG rectangle to work as a background in IE9 or FF4 and neither is working for me. Here's my code:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
<div style="height:99px;background-image: url('bar.svg')"></div>
<iframe src="bar.svg" height="99px"></iframe>
</body>
</html>

The iframe shows the graphic but the div does not. Any ideas where I may be going wrong?

I found a working example here: But I can't make it work myself :( It's been driving me crazy.

Thanks for any help.

like image 474
user169867 Avatar asked Mar 23 '11 18:03

user169867


People also ask

Can I use SVG as background image in 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 you put 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.

Can you embed SVG in HTML?

You can embed SVG elements directly into your HTML pages.

How do I make SVG background transparent in CSS?

The SVG way would be to set the stroke to none , or alternatively set the stroke-opacity to 0 . You also don't set any value for fill on the <rect> element and the default is black. For a transparent rect you want to add fill="none" .


1 Answers

Thanks everyone for the help. It actually was a web server problem where the wrong MIME type for SVG was being served & that made the browsers fail to render correctly.

Here's what fixed it for me.

1st I switched from VS 2010's built-in web server to IIS Express. Then in my web config I added:

<system.webServer>
    <staticContent>
      <mimeMap fileExtension=".svg" mimeType="image/svg+xml" />
    </staticContent>
</system.webServer>

Now everything works correctly.

like image 64
user169867 Avatar answered Oct 02 '22 20:10

user169867