SVG backgrounds are honestly one of the best ways to add visual interest to a website. One example is the breadcrumb bar you see on this page.
Another example is the patterned background you see on Learn JavaScript.
Adding SVG backgrounds
Find or create an SVG pattern
First, you have to find or create an SVG pattern.
The easiest way is to start with one of the many resources out there, like Hero Patterns, Pattern Monster, and SVGBackgrounds.com. Go through them, find the pattern that you like, and download the SVG.
The SVG will typically be a standard SVG that looks like this:
<svg xmlns="http://www.w3.org/2000/svg" width="152" height="152"> <path d="..." fill="#9C92AC" fill-opacity="0.4" /></svg>Convert the SVG into a pattern
What you have to do next is to convert it into a pattern by following these four steps:
- Change the
<svg>tag to<pattern>and keep everything inside. - Keep the
widthandheight— that’s the size of the repeating tile. - Add an
idandpatternUnits="userSpaceOnUse". - Drop the
xmlnsattribute.
<pattern id="temple" patternUnits="userSpaceOnUse" width="152" height="152"> <path d="..." fill="#9C92AC" fill-opacity="0.4"></path></pattern>Then include these patterns into an svg element like this. You can include as
many patterns as you want.
<svg width="0" height="0"> <!-- pattern 1 --> <!-- pattern 2 --></svg>Include the SVG pattern
If you have included the patterns into the HTML, you can use any of the patterns by referencing their #id like this. So if I want to use the temple pattern, I just write that in the fill’s url().
<svg class="w-full h-full"> <rect width="100%" height="100%" fill="url(#temple)"></rect></svg>Making things easier with SVG and SVGBackground components
I typically put all my patterns into a patterns.svg file.
<svg width="0" height="0"> <!-- pattern 1 --> <!-- pattern 2 --></svg>Then I include this patterns.svg with the SVG component at the top of my pages.
---import { SVG } from '@splendidlabz/astro'---
<SVG name="patterns" />Finally, I include the pattern itself with an SVGBackground component. This basically adds the fill: url layer.
---import { SVG, SVGBackground } from '@splendidlabz/astro'---
<SVG name="patterns" />
<section class="stack bg-purple-100"> <SVGBackground pattern="temple" /> <!-- Content goes here --></section>That’s it for SVG backgrounds and patterns!
Code snippets to copy-paste
HTML for patterns.svg
<svg width="0" height="0"> <!-- pattern 1 --> <!-- pattern 2 --></svg>HTML for each pattern
<pattern id="pattern-id" patternUnits="userSpaceOnUse" width="152" height="152"> <!-- Pattern content --></pattern>Using SVG and SVGBackground
---import { SVG, SVGBackground } from '@splendidlabz/astro'---
<SVG name="patterns" />
<section class="stack"> <SVGBackground pattern="temple" /> <!-- Content goes here --></section>Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson