This section of the tutorial covers the basics of using CSS with SVG including how to:
CSS can apply presentation attributes to SVG elements similar to how CSS applies attributes to HTML.
However, only SVG presentation attributes can be applied to SVG through CSS.
In the following example, all elements using the class background
will have a black fill.
const helloSvgCss = css`
.background {
fill: #000000;
}
`;
CSS classes can be applied to SVG Elements like in the example below.
const helloCssClasses = html`
<rect class="background"></rect>
`;
SVG can also be styled with CSS Custom Properties. This enables artists and designers to theme an SVG document with the same styles as its HTML counterpart.
const helloCssCustomProperties = css`
.background {
fill: var(--background-color, #000000);
}
`;
Add the following css template to repeat-pattern.js
. It shouldn't affect repeat-pattern
until the static styles
property has been set.
import {LitElement, html, svg, css} from 'lit';
const svgCSS = css`
:host {
display: block;
}
svg {
height: 100%;
width: 100%;
}
text {
fill: #ffffff;
dominant-baseline: hanging;
font-family: monospace;
font-size: 24px;
}
`;
This demo requires a theme that includes:
background-color
font-color
font-size
stroke-width
stroke-color
To accomplish this, create another CSS template with CSS custom properties representing the required theme.
const themeCSS = css`
.background {
fill: var(--background-color, #000000);
}
text {
fill: var(--font-color, #ffffff);
font-size: var(--font-size, 26px);
stroke-width: var(--stroke-width, 1.2px);
stroke: var(--stroke-color, #eeeeee);
}
`;
Add the CSS templates to the repeat-pattern
custom element.
@customElement('repeat-pattern')
export class RepeatPattern extends LitElement {
static styles = [svgCSS, themeCSS];
...
}
export class RepeatPattern extends LitElement {
static styles = [svgCSS, themeCSS];
...
}
customElements.define('repeat-pattern', RepeatPattern);
Next, add the background
class to the <rect>
representing the background element in our pattern.
export class RepeatPattern extends LitElement {
...
render() {
return html`
<svg height="100%" width="100%">
...
<rect class="background"></rect>
...
</svg>
`;
}
}
Finally add CSS custom properties to the styles in index.html
to theme repeat-pattern
.
:root {
--background-color: #000000;
--font-color: #ffffff;
--font-size: 26px;
--stroke-width: 1.2px;
--stroke-color: #eeeeee;
font-family: 'Open Sans', sans-serif;
font-size: 1.5em;
}
After completing this section, you'll be ready to explore more advanced concepts in SVG and Lit.