Search code examples
csssvgfrontendtailwind-cssinline-styles

Inline CSS - Inline SVG url not showing up as background image


I want to add Inline SVG in inline CSS, but it is not working.

<div style="background: url(data:image/svg+xml,%3Csvg%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20version%3D'1.1'%20preserveAspectRatio%3D'none'%20viewBox%3D'0%200%2010%2010'%3E%20%3Cpath%20d%3D'M%2010%200%20L%200%2010'%20fill%3D'none'%20stroke%3D'red'%20stroke-width%3D'1'%2F%3E%3C%2Fsvg%3E)">rtrtfgf</div>

is supposed to work, but it is not. When I try to do the same in a separate CSS file, it works

.line {
   /*  display:inline-block;
    border: 1px solid #ccc;
    margin: 10px;
    padding: 10px;
    position: relative; */
    background:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' preserveAspectRatio='none' viewBox='0 0 10 10'> <path d='M 10 0 L 0 10' fill='none' stroke='red' stroke-width='1'/></svg>");
}

HTML

<div class="line">LINE!</div>

As per some articles the URL needs to be encoded using encodeURIComponent() for inline CSS, which has been done. If you copy-paste the inline URL in a browser, it will work and you will be able to see the svg to image in the window


Solution

  • There is a difference with the CSS and the inline style attribute value you tried to use – the inline style attribute is missing the double quotes (") inside the url() value.

    However, adding the double quotes means that it ends the quoting for the style attribute value.

    However, you can work around this limitation by removing the quotes around the style attribute value, and removing any space characters. Then the background image will show:

    <div style=background:url("data:image/svg+xml,%3Csvg%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20version%3D'1.1'%20preserveAspectRatio%3D'none'%20viewBox%3D'0%200%2010%2010'%3E%20%3Cpath%20d%3D'M%2010%200%20L%200%2010'%20fill%3D'none'%20stroke%3D'red'%20stroke-width%3D'1'%2F%3E%3C%2Fsvg%3E")>rtrtfgf</div>