All Articles Kinsa Creative

Encode SVG Images into CSS with Python using Base64 Encoding

When changing icons on hover state for example, avoid the flash of unstyled content while the file is retrieved by encoding it directly into the stylesheet.

In Python, open and encode a SVG file into Base64:

import base64
f=open('/path/to/file.svg', 'r')

Copy the byte string output, that is, everything between b' and the closing '.

In CSS, use that as the background image for an element, replacing eggs with the copied byte string value:

spam {
    background: url('data:image/svg+xml;base64,eggs') no-repeat right center; 

Run it as a script. Create a file named and add the following:

import base64
import getopt
import sys

def main(argv):
    helpstr = 'python3 -f "foo.svg bar.svg"'

        opts, args = getopt.getopt(argv, "hf:", ["files="])
    except getopt.GetoptError:
    for opt, arg in opts:
        if opt == '-h':
        elif opt in ("-f", "--files"):
            files = arg

            for file in files.split(' '):
                f = open(file, 'r')
                byte_string = base64.b64encode('utf-8'))
                print(f'background-image: url("data:image/svg+xml;base64,{byte_string.decode("utf-8")}");')

if __name__ == '__main__':

To run it, provide a space separated list of relative file paths to the -f argument as in python3 -f "foo.svg bar.svg". It will print lines for each file which can be copy-pasted directly into CSS to set background images.


Email us at