Use CSS Variable Scope to Color SVG Elements

Jhey Tompkins
InstructorJhey Tompkins
Share this video with your friends

Social Share Links

Send Tweet

Use CSS variables to take the responsibility of coloring SVG away from the markup in this example. Instead of an inline stroke, we can use scoped CSS variables to color the stroke for SVG elements.

Instructor: [0:00] We have our function tic-tac-toe grid, but it doesn't look very appealing. Let's define some color that we can use. Let's start with a background-color, and let's go with HSL(210, 50%, 15%), and we can apply that directly to the body.

[0:16] Then, we can define some colors for our SVG elements. Here, we've defined a color for naughts, a color for crosses, and a color for the lines. We're going to use CSS variable scoping to apply those. We're going to use SVG stroke:var(--stroke). Then on the relevant element, we can set that stroke variable to the color we want. For the border line, we can set stroke to var line.

[0:40] We won't see an update yet, because we still have inline stroke on those elements, so let's remove those strokes. Now, we can see our color is being used for the stroke of the lines. If we update naught and cross to use their stroke, their colors will also be used, as we can see.

[0:56] If we remove our stroke declaration, we'll no longer see the element. That's because we didn't provide a fallback value. If we go back to our SVG declaration and provide a fallback value of black, now we can see our crosses again. Personally, the purple looks a little bit nicer.

[1:15] In review, we can use custom CSS variables to define colors. Then we can use scope styles to define how an element will render for its base styles. Here we're using SVG strokes and we're saying that an SVG will either be stroked with the color defined on a scope or that will fall back to black. To do that we're using the fallback parameter of a CSS variable.