All Articles

SVG fill color doesn't work with hex colors

Problem

Basically, this works fine with fill='red'

background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='20' height='10' ><path fill='red' d='M 0,10 H 20 L 10,0 Z' /></svg>")

This doesn’t work as well with fill='#FF0000'

background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='20' height='10' ><path fill='#FF0000' d='M 0,10 H 20 L 10,0 Z' /></svg>")

Reason and solution

# in URLs starts a fragment identifier. So, in order to make that work, write %23 instead of #. That is the value of escaped # character. It works with fill='%23FF0000'

background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='20' height='10' ><path fill='%23FF0000' d='M 0,10 H 20 L 10,0 Z' /></svg>")

Wondering what is Fragment Identifiers, check this article

https://css-tricks.com/svg-fragment-identifiers-work/

Reference

https://stackoverflow.com/a/61099329/3375906

Demo

Published 17 Mar 2021

Recent Posts

Convert Promise to Observable

You'll need those tips one day if you get used to RxJS 🤣

TypeScript unknown vs any types

The main difference between unknown and any is that unknown is much less permissive than any: we have to do some form of checking before performing most operations on values of type unknown, whereas we don't have to do any checks before performing operations on values of type any.


Follow @tuantrungvo on Twitter for more!