2

I have created a really simple SVG image, logo.svg, containing just a single path with a blue fill and a white stroke.

The issue is that I need to style it differently depending on where I use it on the website:

  • Place 1: Apply drop shadow
  • Place 2: Change fill color
  • Place 3: Change stroke color
  • Place 4: Change stroke width
  • and perhaps more in the future...

What's the best practice in this scenario? Do I need to create multiple files for all kind of "presentations" of my SVG image?

If I have to create multiple files, can I define the path in a single place, so if I need to adjust it in the future I won't have to do it in a gazillion places?

Christoffer Reijer
  • 1,925
  • 2
  • 21
  • 40

1 Answers1

2

SVG can be styled by CSS like HTML, but you need it to either inline it, or include it as an <object>. Then you just need to add the correct selectors to style it.

For example, the same circle is shown as red or green depending on the section it appears:

.section1 circle
{
  fill: #F00;
}

.section2 circle
{
  fill: #0F0;
}
<div class="section1">
<svg>
  <circle cx="50" cy="50" r="50" />
</svg>
</div>

<div class="section2">
<svg>
  <circle cx="50" cy="50" r="50" />
</svg>
</div>

You can find more information about SVG and styling it in CSS-Tricks.

Arturo Torres Sánchez
  • 2,751
  • 4
  • 20
  • 33
  • This is static styling; once the svg is rendered how you would change the style. I believe that is the question – webjockey Nov 17 '16 at 17:50
  • @webjockey The question is about the same logo in different contexts (like on light vs dark backgrounds). It doesn't strike me as dynamic. But if that's the case, classes can be added and removed with JavaScript as needed. – Arturo Torres Sánchez Nov 17 '16 at 17:54