本节教程介绍在 SVG 中使用 CSS 的基础知识,包括如何:

学习

Permalink to "学习"

CSS 可以将展示属性应用于 SVG 元素,类似于 CSS 将属性应用于 HTML 的方式。

但是,只有 SVG 展示属性可以通过 CSS 应用于 SVG。

在以下示例中,所有使用 background 类的元素将具有黑色填充。

const helloSvgCss = css`
.background {
fill: #000000;
}
`;

CSS 类可以像下面的示例一样应用于 SVG 元素。

const helloCssClasses = html`
<rect class="background"></rect>
`;

SVG 也可以使用 CSS 自定义属性来设置样式。这使得艺术家和设计师能够使用与 HTML 对应文档相同的样式来为 SVG 文档设置主题。

const helloCssCustomProperties = css`
.background {
fill: var(--background-color, #000000);
}
`;

实践

Permalink to "实践"

将以下 CSS 模板添加到 repeat-pattern.js 中。在设置 static styles 属性之前,它不会影响 repeat-pattern

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;
}
`;

本演示需要一个包含以下内容的主题:

为此,创建另一个 CSS 模板,使用 CSS 自定义属性来表示所需的主题。

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);
}
`;

将 CSS 模板添加到 repeat-pattern 自定义元素中。

@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);

接下来,将 background 类添加到图案中代表背景元素的 <rect> 上。

export class RepeatPattern extends LitElement {
...
render() {
return html`
<svg height="100%" width="100%">
...
<rect class="background"></rect>
...
</svg>
`;
}
}

最后,在 index.html 中的样式中添加 CSS 自定义属性,为 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;
}

完成本节后,你将准备好探索 SVG 和 Lit 中更高级的概念。