乐闻世界logo
搜索文章和话题

How to change the fill color of an svg path with css

4个答案

1
2
3
4

Changing the fill color of SVG paths in CSS is typically achieved using the fill attribute. First, ensure your SVG is embedded directly in HTML, as CSS may not directly affect the styling of externally referenced SVG files.

Here's a simple example demonstrating how to use CSS to change the fill color of SVG paths:

Assume you have the following SVG code embedded in HTML:

html
<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg"> <path d="M10 10 h 80 v 80 h -80 Z" /> </svg>

In this SVG, we have a <path> element that draws a simple square path. By default, this path has no fill color.

Now, let's add some CSS to change the fill color of this path:

css
svg path { fill: #ff0000; /* Set fill color to red */ }

Add this CSS rule to your stylesheet or embed it directly within an HTML <style> tag; it will change the fill color of all <path> elements within the SVG to red.

This example demonstrates a general method for changing the fill color of all SVG paths, but you can also specify the exact paths you want to change using class names:

HTML:

html
<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg"> <path class="my-path" d="M10 10 h 80 v 80 h -80 Z" /> </svg>

CSS:

css
svg .my-path { fill: #00ff00; /* Set fill color of paths with class `my-path` to green */ }

In this example, only SVG paths with the class my-path will have their fill color changed to green. This approach allows you to selectively change the styles of specific elements without affecting others.

2024年6月29日 12:07 回复

You can apply this CSS to the SVG circle element.

css
svg:hover circle{ fill: #F6831D; stroke-dashoffset: 0; stroke-dasharray: 700; stroke-width: 2; }
2024年6月29日 12:07 回复

Apply to all SVGs: fill="var(--svgcolor)"

In CSS: :root { --svgcolor: tomato; }

Using pseudo-classes: span.github:hover { --svgcolor: aquamarine; }

Explanation root: the root element (representing the HTML document). --svgcolor: CSS variable. span.github: selects a span element with the 'github' class containing an SVG icon and applying the hover pseudo-class.

2024年6月29日 12:07 回复

If you want to change the fill color when hovering over the element, try the following:

css
path:hover{ fill:red; }
2024年6月29日 12:07 回复

你的答案