kingkapd
kingkapd

Reputation: 69

Having trouble styling SVG with CSS?

Hi I'm new to using SVG's but i thought the whole idea of SVG's is that you can change the background-color etc. Anyway i'm using the open sources clrs.cc and it has both svg fills and strokes built in but none work on my search icon.

<img src="ic_search_48px.svg" class="fill-navy" alt="This should be a search icon">

Here is what the CSS classes look like:

.fill-navy {
 fill: #001F3F; }

Thanks for helping out!

Upvotes: 0

Views: 100

Answers (1)

Paulie_D
Paulie_D

Reputation: 115383

Basically, you cannot change the color of an SVG used as an actual image or background-image.

CSS can only affect inline SVG in the page HTML.

EG.

.hidden {
  display: none;
}
.icon {
  width: 48px;
  height: 48px;
}
.large {
  width: 96px;
  height: 96px;
}
.red {
  fill: red;
}
.green {
  fill: green;
}
<svg xmlns="http://www.w3.org/2000/svg" class="hidden">
  <defs>
    <g id="search" viewBox="0 0 48 48">
      <path d="M31 28h-1.59l-.55-.55C30.82 25.18 32 22.23 32 19c0-7.18-5.82-13-13-13S6 11.82 6 19s5.82 13 13 13c3.23 0 6.18-1.18 8.45-3.13l.55.55V31l10 9.98L40.98 38 31 28zm-12 0c-4.97 0-9-4.03-9-9s4.03-9 9-9 9 4.03 9 9-4.03 9-9 9z" />
    </g>
  </defs>
</svg>

<svg class="icon" viewBox="0 0 48 48">>
  <use xlink:href="#search" class="red" />
</svg>

<svg class="icon large" viewBox="0 0 48 48">>
  <use xlink:href="#search" class="green" />
</svg>

  1. Extra Reading - Article @ CSS-Tricks.com
  2. Also - SVG Icons @ CSS-Tricks.com

Upvotes: 2

Related Questions