SVG images are displayed on the page in the form of https links, and can inherit the color and size of the parent class (similar to Alibaba iconfont)

1. Background and Problems

1. Background

In the front-end project development process, we often use the font icon library (iconfont) , taking ant dezign as an example.

If we encounter icons that do not exist in the icon library, we often use custom icons :

  • Introduce a custom svg diagram as a component
  • But not any type of svg can inherit the color and font size of the parent class, you need to set the properties of the svg: width=”1em” height=”1em” fill=”currentColor”

2. Questions

  • When we have such requirements: navigation icons are configurable and full stack skinning is possible.

  • Method to realize:

    In order to achieve full-stack skinning, we need to display icons in the form of svg ,
    but the icons are configured by taking the http link to the background after uploading to Alibaba Cloud, so
    this method will be invalid.

Second, the solution ( how [svg] links are embedded in HTML and rendered)

1. The rookie tutorial provides three options : (❌)

Although this method can display svg images, it cannot select html elements to change the style to achieve the effect of skinning. Because embed, object, and iframe are all style-isolated.

2. Use the xxx/> tag directly, but this method will also face the above problems. (❌)

3. Use element.innerHtml = the requested svg string, but this method has security risks of XSS attack. (❌)

4. Use background-color + mask-image. (✅)

mask-image: CSS property used to set the image of the mask layer on the element.

How to use:
When we add a mask layer image to the colored background image, a similar effect can be displayed, and it is more appropriate to use the curve to save the country.
In fact, mask-image has many uses: CSS mask CSS3 mask/masks is introduced in detail , if you are interested, you can go to Kangkang

Third, write at the end

This problem was explored for a long time before I found a practical solution, and I wrote it down for everyone. If you have a better solution, please comment!
There are always all kinds of strange problems in the development. You are welcome to share the strange problems you have encountered, and we will discuss them together.

Leave a Comment

Your email address will not be published. Required fields are marked *