简体   繁体   中英

What is the purpose of fill attribute on svg tag?

As far as I know, SVG fill attribute is used to paint the object. And as per theMDN 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?

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 class="icon icon-prefix-home" 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 class="icon icon-prefix-home" 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 eg 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" class="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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM