Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Background" style property ignored for <svg> elements inside of other <svg> elements

Tags:

css

styling

svg

A simple experiment with two nested <svg> elements shows:

  • The outer <svg> element has the background style property applied
  • The inner <svg> element does not have the background style property applied

Another experiment adds a transform attribute to both <svg>s shows that this attribute is also ignored by the inner <svg>.

Any reason why the inner <svg> element ignores properties like background styling and transform? In general, is there documentation of which attributes are and aren't applied to nested <svg> elements?

like image 733
Walmink Avatar asked Jun 04 '18 08:06

Walmink


People also ask

Can svgs be nested?

The SVG format allows for the nesting of SVG graphics. It is possible for an “<svg>” elements, to be placed within another “<svg>” element.

Does Z-Index work with SVG?

The z-index only works on the complete content. This is because the HTML rendered controls the positioning before handing off to the SVG rendered to place the internal SVG contents. So, basically there is no z-index for SVG, it uses the painters model.

What CSS is used to apply styles within SVG elements?

Presentation attributes are used to style SVG elements and can be used as CSS properties.

Can we add style to SVG?

The SVG <style> element allows style sheets to be embedded directly within SVG content. Note: SVG's style element has the same attributes as the corresponding element in HTML (see HTML's <style> element).


1 Answers

The issue is that, when an <svg> is embedded in HTML, it kind of does double-duty as both an SVG element and an HTML one.

For consistency, some HTML features work with the outermost <svg> elements, but they don't work for inner/nested SVG elements. Remember, SVG is a different standard to HTML. It has a different purpose, and it doesn't make sense for all HTML features to work with SVG elements. Having said that, where it makes sense, certain HTML features are supported, or will be supported soon.

One early addition was making background/background-color work with outermost <svg> elements. AFAIK all browsers support that now.

The same applies to transform. The current SVG spec (1.1) does not allow transform on the <svg> element, but for consistency with other HTML elements, browsers support it for outermost <svg> elements. In the upcoming SVG 2 standard, transform will be allowed on inner <svg> elements as well. In fact Firefox has already implemented that. I believe it is currently the only browser that does.

If you want an approach that works everywhere, the following usually does the trick.

<svg ...>
  <rect width="100%" height="100%" fill="#00f"/>
  ...
</svg>
like image 102
Paul LeBeau Avatar answered Sep 28 '22 13:09

Paul LeBeau