Reputation: 407
I've come across a strange behaviour (bug?) for rendering SVGs in Chrome. I want to use a SVG sprite in a background-image. This way I want to have access to multiple colors by just setting the background-position accordingly. While this seems to work Chrome is offsetting the SVG so it does not render at the correct position. It kinda looks like the background-position is not at (0, 0)...
Interesstingly Chrome is not always offsetting it... By changing the values of width/height of the div the SVG snaps back to the correct position for some widths/heights. Here is a pen I created to showcase the problem: https://codepen.io/thoro/pen/XpedPR
If you open the pen in Chrome, the arrow sprite will be offset and therefore the black arrow not fully visible. By changing the $box property to 66px the arrow will snap to the correct position just to be offset again when increasing the number...
In Firefox the arrow is rendering as expected. (IE is a whole other story but does not matter here)
My SVG I am trying to display:
<svg xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 120">
<title>grid-link</title>
<symbol id="my" viewBox="0 0 10 120">
<path d="M6.1 7.7l.6.6L10 5 6.7 1.7l-.6.6 2.3 2.3H0v.8h8.4L6.1 7.7z"/>
</symbol>
<use xlink:href="#my" y="0" fill="#000"/>
<use xlink:href="#my" y="110" fill="#fff"/>
</svg>
Am I doing something wrong? Is there any way to fix this?
The problem can be fixed by removing the viewBox and using width and height instead:
<svg xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg" width="10" height="110">
<title>grid-link</title>
<symbol id="my">
<path d="M6.1 7.7l.6.6L10 5 6.7 1.7l-.6.6 2.3 2.3H0v.8h8.4L6.1 7.7z"/>
</symbol>
<use xlink:href="#my" y="0" fill="#000"/>
<use xlink:href="#my" y="110" fill="#fff"/>
</svg>
Upvotes: 2
Views: 3786
Reputation: 262
Your problem is with ViewBox. You specify a ViewPort (via the div's width and height) of 65 by 65, but set the ViewBox height as 120.
If you remove ViewBox completely from your SVG it fixes the problem you describe (and makes the resulting icon scalable as you change $box).
Sara Soueidan has a very useful write-up of ViewPort, ViewBox and the SVG coordinate system on her blog: https://sarasoueidan.com/blog/svg-coordinate-systems/.
Upvotes: 2