M
M
mimocrocodile2020-07-11 00:22:58
css
mimocrocodile, 2020-07-11 00:22:58

SVG icons on the site. How to insert correctly?

5f08dc1d80be5302475483.jpegA question about SVG icons, namely: what is the best way to insert icons on a page?

I found many ways on major sites. And all these methods are different. I can't figure out what are the advantages of one over the other.

What I found:
- Inserting svg code into <span>, i.e. image code directly in the html document.
- Paste directly into - The same paste through the tag. (but specific...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FabiBoom, 2020-07-11
@mimocrocodile

  • Insertion through the img element - if you have a content image (contain something important for the user), for example, a logo.
  • Inserting via as background-image: url() - if your image is decorative (regular icons, like in your examples) and does not change in any way during user interaction (more on that below). For example, for simple icons for section headings, you can use the ::after and ::before + background-image pseudo-elements with the url to the svgshku. Does not litter the markup in this way.
  • Inserting through the svg element directly into the code - if you have a decorative image and you will need to under some conditions, for example, change the fill of the svg or the color of the stroke using CSS. For example, a red icon in a button turns white when hovering over the button. The problem is that in order to change its color through CSS in the pseudo-element way, we can only replace it with another image of the same image, but with white color. And you can do this on hover:
    button:hover svg {
       fill: white;
    }

    And that's all - turn to this icon and fill it with white. Therefore, in order to control the possibilities of svg through styles, this SVG must be in the markup.
There are many options for use and here you should look at the specific situation.
There is also the possibility not to add all the svg code to the markup, but to use svg sprites, which I highly recommend. They are also great to manage through CSS, it simplifies the markup, especially if some icon is used repeatedly. Here are a couple of links:
One
Two

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question