Wolfgang
Wolfgang

Reputation: 896

Is there an easy way to style a svg path element like a div with 3d border?

I need a 3d border on my svg shapes. My svgs are created at runtime (in javascript) and do have flexible width/height (should not matter). And of course they have more complex shapes than the given example below. It's just the simplest example I can think of to show you what I am trying to achieve.

<div class="sample"></div>

css:

.sample {
  width:300px;
  height:150px;
  background-color: red;
  border-radius:20px;
  border: solid 15px green;
  border-top-color: blue;
  border-left-color: blue;
}

Didn't want to post a picture here and there is no usable svg code so here is the fiddle to show what it should look like: css example

All my shapes are containing vertical and horizontal lines only (+ border radius)

Upvotes: 0

Views: 357

Answers (1)

ccprog
ccprog

Reputation: 21876

The most important matter is how exact you want to get. If we are talking about stroke-widths of only one or two pixels, it will not matter much, but in the example below the differences in the details can be seen.

The radii of the borders do not match on all corners, and the color change does not occure in the right place. The corners of the fill area are not rounded; for that you would have to really draw arc path segments.

If you have multiple, non-overlapping paths, you could group them in a <g> element and then reference only this one group in the <use> elements.

path {
    fill: blue;
}
use.upper {
    stroke: red;
    stroke-width: 40;
    stroke-linejoin: round;
}
use.lower {
    stroke: green;
    stroke-width: 20;
    stroke-linejoin: round;
}
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
     width="300" height="250">
  <use class="upper" xlink:href="#path1" />
  <use class="lower" xlink:href="#path1" x="10" y="10" />
  <path id="path1" d="M60,60 H160 V120 H240 V200 H60 Z" />
</svg>

For anything more concerned with precision, you might need to compute the forms you want to achieve in your Javascript code.

It might be tempting to look at filter effects, but again, multi-colored border effects will lack in precision. For blurred drop shadow effects, they are a great choice, but for clearly-defined borders their performance is worse than this technique with <use> elements.

Upvotes: 1

Related Questions