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

This post is part of my Today I learned series in which I share all my learnings regarding web development.

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 ; }

< path stroke-width = " 3 " > </ path >

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 ; }

< path stroke-width = " 3 " paint-order = " stroke " > </ path >

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. 🎉

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