1

I have 4 elements on the page which use the same svg gradient

<svg> <defs> <linearGradient id="gradient"> <stop offset="0%" style="stop-color: deepPink"></stop> <stop offset="100%" style="stop-color: #009966"></stop> </linearGradient> </defs> </svg>

And I just want to define it once on the page and it isn't supposed to be visible. But this svg block move other blocks on the page and has dimensions 150x300

These svg blocks are supposed to be visible on the page and use the above svg gradient.

<svg> <rect width="100" height="100" stroke="#eee" stroke-width="5" fill="url(#gradient)"></rect> </svg> <svg> <rect width="100" height="100" stroke="#eee" stroke-width="5" fill="url(#gradient)"></rect> </svg>

Alex Vasilev
  • 765
  • 8
  • 19

4 Answers4

6

The following CSS worked for me to hide the block.

svg defs {
  height: 0;
  position: absolute;
  width: 0;
}

As stated in other answers, display:none will break the def and visibility:hidden still takes space on the page.

Doug Hamlin
  • 996
  • 1
  • 11
  • 17
  • 1
    visibility:hidden also makes any mask elements in the def unusable – Panos Theof Jun 20 '17 at 15:24
  • I've made myself a helper class `.is-off-screen` with these styles and `left: -9999em;` that I'm using to hide my SVG symbols as I saw issues with SVGs using 'map' when using `visibility: hidden`. – Crafty Cat Sep 28 '20 at 09:32
2

If you want to hide the definition SVG give it width and height attributes of 0

Robert Longson
  • 118,664
  • 26
  • 252
  • 242
2

The default value for the width and height attributes on the svg element is 100%, which means the SVG viewport depends on the parent container it's in.

From the w3 spec:

The SVG user agent negotiates with its parent user agent to determine the viewport into which the SVG user agent can render the document.

To solve your issue you can set the width and height attributes to 0 directly on the svg tag, but it's also possible to use CSS.

To prevent svg elements to take up space on the page use display: none. I'm not sure about browser support of gradients in this case, but there are work arounds. Check this Bugzilla post.

U r s u s
  • 6,680
  • 12
  • 50
  • 88
0

This is an alternative way that works for me. I set width and height attribute to 0 and also set the display attribute to none like this.

<svg width="0" height="0" display="none">
  <defs>
    <g id="my-object">...</g>
  </defs>
</svg>
worrawut
  • 958
  • 10
  • 17