Adding SVG to the Block Editor

Out of the box, WordPress does not allow uploading SVG files for security reasons. If you want to be able to upload SVGs into the block editor (or anywhere else in WP) there are some plugins to activate the support for SVGs like any other image.

But one thing that is not possible, if an SVG is included in an image tag, is to style or animate them with CSS. So, something like this won’t have any effect.

svg {
    fill: #333;
}Code language: CSS (css)

In my case I wanted to include some logos on a page, but because the site has a dark and a light mode, I wanted to be able to control the colors inside the SVG when the color-scheme switches. I could have added two separate SVG files for each color version, add CSS classes to them and hide/display each accordingly, but this would also mean a second image would be downloaded. To be able to style the colors directly with CSS, I needed to add them inline to the HTML.

The easiest way I found, is by adding a “Custom HTML” block and then place the (optimized) SVG code in there. If you switch to the “preview” mode you even see the image in the editor. Also I add a class .svg-logo to the block under the “Advanced” settings.

Now, if we add the following styles to our CSS file we can control things like fill or stroke with CSS.

.svg-logo svg {
    fill: #333;
}

@media ( prefers-color-scheme: dark ) {
    .svg-logo svg {
        fill: #eee;
    }
}Code language: CSS (css)

Maybe there’s an easier/better way of adding inline SVGs (if so, let me know), but this worked pretty good for me so far.

PS: The styles for a dark mode will quite possibly be more complicated than the example above, using classes or data-attributes and what not. The example should give you an idea of how to style the colors, but is not meant as a complete working solution.

PPS: After writing this, I found out that the “Support SVG” plugin has some functionality to inline the SVGs you add, but it looks like this is done with JS in the browser, which I don’t particularly liked. My wish would be for something that works basically like the image block, but lets you choose to inline the SVGs right on the server.

Made with ❤️ in Switzerland