DEV Community

Cover image for SVG Patterns Made Easy
netsi1964 šŸ™šŸ»
netsi1964 šŸ™šŸ»

Posted on

SVG Patterns Made Easy

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
}
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

See the example on CodePen

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs