DEV Community

Stefan Judis
Stefan Judis

Posted on • Originally published at stefanjudis.com on

TIL: The paint order of SVG elements and their stroke and fill is configurable

Dealing with SVG can be fiddly at times. Sometimes you only want to adjust the border aka stroke of a path or rect to find out that it changes the visual appearance in a way that you didn't expect.

You can define an element's stroke-width in CSS or a presentation attribute.

path {
  stroke-width: 3;
}
Enter fullscreen mode Exit fullscreen mode
<path stroke-width="3"></path>
Enter fullscreen mode Exit fullscreen mode

If you increase the stroke width by more than a few pixels you'll see that the stroke width will change to both sides - inside and inside of the SVG element.

I always started to change the path or width/height of the given element to avoid the stroke going over the fill too much. It turns out that you can also change the paint order of fill and stroke using paint-order.

path {
  // fill will go over stroke
  paint-order: stroke;
}
Enter fullscreen mode Exit fullscreen mode
<!-- fill will go over stroke -->
<path stroke-width="3" paint-order="stroke"></path>
Enter fullscreen mode Exit fullscreen mode

This way, the stroke is painted first followed by the fill color. You can then expand the stroke width as much as you want and it will look like it's expanding only to the outside because the fill color will be on top of the stroke. 🎉

Visualisation showing the effect of paint-order

If you want to learn more about this check the MDN article or play around with it on CodePen.

Top comments (1)

Collapse
 
drmandible profile image
DrMandible

Nifty!