1
votes

I want to have an inline SVG fill the whole width of the browser window. The SVG has some content outside of the viewBox. This is the SVG file: http://pastebin.com/F5irDNai

What happens when I set the width to 100% is that the content outside of the viewBox gets visible:

svg {
  width: 100%;
}

See this jsfiddle: https://jsfiddle.net/3w2hy8kv/1/ The red rectangle is the viewBox boundary.

What I want is to have the viewBox of the SVG fill whole browser window horizontally without the content outside of the viewBox appearing. Is that possible?

1
doesn't overflow: hidden; work?Robert Longson
No, I have tried that on both the parent element, body and the svg itself and I does not hide the content outside viewBox. Whenever the width is larger than the viewBox the content outside of the viewBox appears.Dag Henning Liodden Sørbø
You need to look at the preserveAspectRatio attribute. Also try putting a border on the div to see where that goes. Other things to look for: svgomg to optimize your svg, sara souedan's articles on preserveAspectRatio. closest to what you want I got with preserveAspectRatio="xMinYMid slice" on the svg elementRuskin
overflow:hidden clips to the viewport not the viewbox... you can use a clipPath to clip to the viewbox... stackoverflow.com/questions/24074216/…Holger Will
@Ruskin: preserveAspectRatio was the key. Thanks!Dag Henning Liodden Sørbø

1 Answers

1
votes

Thanks to @Ruskin and SVG viewbox showing showing off-screen items who got me in the right direction.

Attribute added to the svg element:

preserveAspectRatio="xMidYMin slice"

It also works adding this attribute with JavaScript.

CSS:

html, body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}

#theSVG svg {
  width: 100%;
  height: 100%;
}

See updated fiddle: https://jsfiddle.net/74cc07m1/1/

EDIT: Fiddle updated with optimized SVG: https://jsfiddle.net/74cc07m1/2/