Home > Software engineering >  What is the purpose of fill attribute on svg tag?
What is the purpose of fill attribute on svg tag?

Time:02-03

As far as I know, SVG fill attribute is used to paint the object. And as per the MDN docs, fill is applicable on following elements:

<altGlyph> | <circle> | <ellipse> | <path> | <polygon> | <polyline> | <rect> | <text> | <textPath> | <tref> | <tspan>

However, the root svg element also accepts the fill property. Initially, I thought it is setting the background-color for the SVG but that is not the case!

So what is the use of this property on svg tag?

CodePudding user response:

A common use case: Icon Coloring
All child elements will inherit the parent fill property:

svg {
  display: inline-block;
  width: 5em;
}

body {
  color: red
}
<svg  id="icon-prefix-home" viewBox="0 0 34 48" fill="currentColor">
  <path d="M33.16,28.12h-5.2v13h-3.44v-16.72l-7.72-8.72l-7.72,8.72v16.72h-3.44v-13h-5.24l16.4-17.4Z" />
</svg>

<svg  id="icon-prefix-home" viewBox="0 0 34 48" fill="currentColor">
  <path fill="green" d="M33.16,28.12h-5.2v13h-3.44v-16.72l-7.72-8.72l-7.72,8.72v16.72h-3.44v-13h-5.24l16.4-17.4Z" />
</svg>

This method can be useful if your svg contains many assets to be reused e.g as <use> instances:

svg{
  display:inline-block;
  height:1em;
  vertical-align:-0.1em;
}

a{
  color: red;
  font-size:5em;
  text-decoration: none
}
<svg id="svgIcons"  viewBox="0 0 100 100" style="display:none" xmlns="http://www.w3.org/2000/svg" >
      <symbol id="home" viewBox="0 0 34 48">
        <path d="M33.16,28.12h-5.2v13h-3.44v-16.72l-7.72-8.72l-7.72,8.72v16.72h-3.44v-13h-5.24l16.4-17.4Z" />
      </symbol>
      <symbol id="close" viewBox="0 0 27 48">
        <path d="M26.16,17.92l-10.44,10.44l10.44,10.44l-2.44,2.44l-10.44-10.44l-10.44,10.44l-2.44-2.44l10.44-10.44l-10.44-10.44l2.44-2.44l10.44,10.44l10.44-10.44Z" />
      </symbol>
</svg>

<a href="#">
  <svg viewBox="0 0 34 48" fill="currentColor">
    <use href="#close" />
  </svg> currentColor
</a>

<a href="#">
  <svg viewBox="0 0 34 48">
    <use href="#home" />
  </svg> default Color
</a>

  •  Tags:  
  • Related