Default background color of SVG root element

It is the answer of @Robert Longson, now with code (there was originally no code, it was added later):

<?xml version="1.0" encoding="UTF-8"?>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg">
 <rect width="100%" height="100%" fill="red"/>
</svg>

This answer uses:

  • https://stackoverflow.com/a/11293812/6747994
  • https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Fills_and_Strokes

Found this works in Safari. SVG only colors in with background-color where an element's bounding box covers. So, give it a border (stroke) with a zero pixel boundary. It fills in the whole thing for you with your background-color.

<svg style='stroke-width: 0px; background-color: blue;'> </svg>


SVG 1.2 Tiny has viewport-fill I'm not sure how widely implemented this property is though as most browsers are targetting SVG 1.1 at this time. Opera implements it FWIW.

A more cross-browser solution currently would be to stick a <rect> element with width and height of 100% and fill="red" as the first child of the <svg> element, for example:

<rect width="100%" height="100%" fill="red"/>

Let me report a very simple solution I found, that is not written in previous answers. I also wanted to set background in an SVG, but I also want that this works in a standalone SVG file.

Well, this solution is really simple, in fact SVG supports style tags, so you can do something like

<svg xmlns="http://www.w3.org/2000/svg" width="50" height="50">
  <style>svg { background-color: red; }</style>
  <text>hello</text>
</svg>

Tags:

Svg