The setSVGAsBackground
function elegantly uses SVGs as repeating patterns in web design, a method that combines functionality with aesthetic appeal.
TL;DR
Discover an uncomplicated yet powerful way to use SVG for background patterns in web design, crafted by ChatGPT from a prompt by Netsi1964
function setSVGAsBackground(svgElement) {
// Efficient code to transform SVG into a background pattern
}
The function can be used to generate a css custom property (css variable) which can then be used to use the SVG as a (repeating) pattern in say you body
element. This allows you to scalable repeating patterns, and using the css clamp function you can have a combination of a minimum, prefered and maximum size of the pattern:
body {
background-image: var(--pattern);
background-size: clamp(50px, 15%, 200px);
}
In this example I use the generated pattern --pattern
on the body where the pattern will be no smaller than 50px
and no larger than 200px
and going for a prefered size of 15%
which will make the pattern grow and shrink in size as the viewport resizes - all done without javascript :-)
// Usage:
// Assuming svgElement is the SVG DOM element you want to use as a pattern
setSVGAsBackground(dynamicPattern);
See the example on CodePen
Top comments (0)