Explain Codes LogoExplain Codes Logo

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

html
responsive-design
best-practices
web-development
Anton ShumikhinbyAnton Shumikhin·Jan 18, 2025
TLDR

stroke-width can be selectively applied to SVG sides by creating individual <path> elements for each side that needs to be targeted. Here’s an example with separate paths for distinct stroke control:

<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg"> <!-- This rectangle walks into a bar... But it's invisible! --> <rect width="100%" height="100%" fill="none" /> <!-- Stroke top side; It's like "top of the morning" but for SVGs --> <path d="M 10,10 H 90" stroke="black" stroke-width="1"/> <!-- Stroke right side; Right side for the right guys! --> <path d="M 90,10 V 90" stroke="black" stroke-width="1"/> </svg>

Manipulate stroke-dasharray

When stroke-width:1 needs to be set on one side of a shape, one could use the stroke-dasharray property. It allows to craft the precise illusion of varying stroke widths:

<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg"> <rect x="10" y="10" width="80" height="80" stroke-dasharray="80, 160" stroke-dashoffset="80" stroke="black" fill="none"/> </svg>

Here we set stroke-dasharray to create a dash length equal to the side we want stroked, and a gap twice as long to avoid coloring the next side of the shape.

Masking and clip-paths for better control

Even though SVG vector effects have limitations, using masks and clip-paths can give us precise control over the strokes of our shapes:

<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg"> <defs> <clipPath id="clip-top"> <rect x="10" y="10" width="80" height="10" /> </clipPath> </defs> <rect x="10" y="10" width="80" height="80" stroke="black" stroke-width="1" clip-path="url(#clip-top)" /> </svg>

The clip-path is used here to allow the stroke to be visible only on the top side.

Tackle limitations with multiple shapes

For more complex stroke-width patterns, creating multiple SVG shapes is the way to go:

<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg"> <!-- Stroke top side; Remember, top strokes rise above the rest! --> <rect x="10" y="10" width="80" height="1" fill="black" /> <!-- Stroke right side; We stroke right, we never stroke wrong! --> <rect x="89" y="10" width="1" height="80" fill="black" /> </svg>

Make use of polyline

The <polyline> element is handy at controlling specific sides and not creating a full border around the shape:

<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg"> <!-- No need to color inside the lines here --> <polyline points="10,10 90,10 90,11 11,11" fill="black" /> </svg>

Apply classes for reusability

Creating classes with stroke-dasharray values can make your code reusable and maintainable:

<style> /* It's stroke time! */ .stroke-top { stroke-dasharray: 80, 160; stroke-dashoffset: 80; } </style>