如何在 CSS 中为 SVG 元素添加边框/轮廓/描边?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18330344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 00:01:43  来源:igfitidea点击:

How to add border/outline/stroke to SVG elements in CSS?

csssvgd3.jsborder

提问by Hugolpz

I'am injecting SVG elements into a webpage thanks to D3js. I have difficulties to style these elements since syntaxes like

由于 D3js,我将 SVG 元素注入到网页中。我很难设计这些元素的样式,因为语法如下

path { border: 3px solid green; }

doesn't work.

不起作用。

How to add border/outline/stroke to SVG elements in webpages with CSS ?

如何使用 CSS 为网页中的 SVG 元素添加边框/轮廓/描边?

回答by Hugolpz

In CSS, something like:

在 CSS 中,类似于:

path {
  fill: none;
  stroke: #646464;
  stroke-width: 1px;
  stroke-dasharray: 2,2;
  stroke-linejoin: round;
}

回答by Sergey Rudenko

For the question: How to add border/outline/stroke to SVG elements in webpages with CSS ?

对于问题:如何使用 CSS 为网页中的 SVG 元素添加边框/轮廓/描边?

You can do in CSS:

你可以在 CSS 中做:

path { outline: 3px solid green; }

Please note as of 2018 it is supported by chrome and safari, but might not be available across all modern browsers. See example below:

请注意,截至 2018 年,Chrome 和 safari 都支持它,但可能不适用于所有现代浏览器。请参阅下面的示例:

I applied outline via CSS to a <g>group with paths inside. In static it looks good. In dynamic (dragging) I can see periodically these artifacts (to the left)

我通过 CSS 将大纲应用到一个<g>包含路径的组中。在静态它看起来不错。在动态(拖动)中,我可以定期看到这些工件(向左)

enter image description here

在此处输入图片说明

UPDATE:

更新:

  • if outline is "solid" - there are no artifacts
  • safari mobile doesn't support outline on <g>elements...
  • 如果轮廓是“实心的”——没有伪影
  • safari mobile 不支持<g>元素的轮廓...

回答by Souleste

Try adding dropshadows.

尝试添加阴影

It doesn't look as clean here as it does in my codepens, but could still be useful.

它在这里看起来不像在我的代码笔中那么干净,但仍然很有用。

svg {
  filter: drop-shadow(1px 1px 0px #111) drop-shadow(-1px 1px 0px #111) drop-shadow(1px -1px 0px #111) drop-shadow(-1px -1px 0px #111);
}

.arr {
  fill: none;
  stroke: #5457ff;
  stroke-width: 5;
  stroke-linecap: round;
  stroke-linejoin: round;
}
<svg height="45" width="40">
  <g class="arr"><path d="m 5 20 l 15 -15 l 15 15 m -15 0 l 0 20"/></g>
</svg>