How to set a stroke-width:1 on only certain sides of SVG shapes?

user782860 picture user782860 · Jan 23, 2012 · Viewed 51.2k times · Source

Setting a stroke-width: 1 on a <rect> element in SVG places a stroke on every side of the rectangle.

How does one place a stroke width on only three sides of an SVG rectangle?

Answer

Erik Dahlstr&#246;m picture Erik Dahlström · Jan 25, 2012

If you need stroke or no-stroke then you can also use stroke-dasharray to do this, by making the dashes and gaps match up with the sides of the rectangle.

rect { fill: none; stroke: black; }
.top { stroke-dasharray: 0,50,150 }
.left { stroke-dasharray: 150,50 }
.bottom { stroke-dasharray: 100,50 }
.right { stroke-dasharray: 50,50,100 }
<svg height="300">
    <rect x="0.5" y="0.5" width="50" height="50" class="top"/>
    <rect x="0.5" y="60.5" width="50" height="50" class="left"/>
    <rect x="0.5" y="120.5" width="50" height="50" class="bottom"/>
    <rect x="0.5" y="180.5" width="50" height="50" class="right"/>
</svg>

See jsfiddle.