Linking to CSS in an SVG embedded by an IMG tag

前端 未结 3 924
离开以前
离开以前 2020-11-28 12:59

I have a page, that includes several SVG files. To synchronize the styling of those SVG files I wanted to create a single stylesheet to hold all styling information.

相关标签:
3条回答
  • 2020-11-28 13:10

    For privacy reasons images must be standalone files. You can use CSS if you encode the stylesheet as a data uri. E.g.

    <?xml version="1.0" standalone="no"?>
    <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" 
    "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
    <?xml-stylesheet type="text/css" href="data:text/css;charset=utf-8;base64,cmVjdCB7IA0KICAgIHN0cm9rZTogYmxhY2s7DQogICAgZmlsbDogZ3JlZW47DQp9" ?>
    <svg version="1.1"
        xmlns="http://www.w3.org/2000/svg"
        viewBox="0 0 100 100"
        >
        <rect x="10" y="10" width="80" height="80" />
    </svg>
    

    There are various online converters for data URIs.

    0 讨论(0)
  • 2020-11-28 13:22

    The answers above are great. I found it simplest, though, to just embed the raw SVG tag itself on my webpage. This allowed the SVG to inherit font-family styles declared in my page's CSS without issue...

    0 讨论(0)
  • 2020-11-28 13:31

    An alternative is to use the <object> tag in your html :-

    <object type="image/svg+xml" data="pic.svg" width="100" height="100"></object>
    

    It's a BIG shame the <img> tag won't work. I don't want to mess about hacking with converting the SVG to a data URI. It's to do with cross-site vulnerabilities on indirectly loading resources and the use of an "Open Redirector".

    Note that in my testing lastnight, the <img> tag method DOES work in IE10, but neither Chrome nor FireFox.

    I don't know why <object> is allowed and <img> isn't. An oversight?

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