Use SVG glyph tag in HTML

后端 未结 1 1990
臣服心动
臣服心动 2021-01-28 17:36

I have an icons.svg file with this source:




        
相关标签:
1条回答
  • 2021-01-28 18:15

    There is no browser that implements SVG <font> or <glyph>. The best you can do is convert the glyphs to <symbol>s containing a <path>, like in a SVG sprite sheet. (This conversion could be even automated with XSLT.) If you set a viewBox for the symbol with the width matching horiz-adv-x and the height the font's ascent, you can position the icon use reliably inline:

    .icon, symbol {
        overflow: visible
    }
    .icon {
        height: 1em
    }
    <svg xmlns="http://www.w3.org/2000/svg" display="none">
      <symbol id="arrow-left" viewBox="0 0 1308 960">
        <!-- font paths are upside-down! -->
        <path transform="matrix(1 0 0 -1 0 960)" d="..." />
      </symbol>
      <symbol id="arrow-up" viewBox="0 0 1308 960">
        <!-- borrowed a font-awesome icon to show an example, width is too small -->
        <path transform="matrix(1 0 0 -1 0 960)" d="m 1006.87,353.125 q 0,-31.875 -23.12,-56.25 l -46.875,-46.875 q -23.75,-23.75 -56.875,-23.75 -33.75,0 -56.25,23.75 l -183.75,183.125 v -440 q 0,-32.5 -23.438,-52.8125 -23.437,-20.3125 -56.562,-20.3125 h -80 q -33.125,0 -56.563,20.3125 -23.437,20.3125 -23.437,52.8125 v 440 l -183.75,-183.125 q -22.5,-23.75 -56.25,-23.75 -33.75,0 -56.25,23.75 l -46.875,46.875 q -23.75,23.75 -23.75,56.25 0,33.125 23.75,56.875 l 406.875,406.875 q 21.875,23.125 56.25,23.125 33.75,0 56.875,-23.125 l 406.875,-406.875 q 23.12,-24.375 23.12,-56.875 z" />
      </symbol>
      <symbol id="arrow-down" viewBox="0 0 860 960">
        <path transform="matrix(1 0 0 -1 0 960)" d="..." />
      </symbol>
    </svg>
    
    <p style="font-size:32px">text <svg viewBox="0 0 1308 960" class="icon"><use xlink:href="#arrow-up"/></svg> text</p>

    The downside is that you don't get the automatic advance that glyphs would give you. The best you can do is to set a constant height and a viewBox for each referencing <svg> that matches that of the symbol you are using.

    If you don't use the icons in a inline context where the advance is important, you could maybe set all symbol viewBox widths to a unified value (i. e. viewBox="0 0 1024 960") and then leave off the viewBox from the icon svg, seting instead a constant width/height ratio (i.e. width:1.067em; height:1em). Some icons will then overflow that box in the horizontal direction.

    0 讨论(0)
提交回复
热议问题