演示属性与内联样式

Avatar of Chris Coyier
Chris Coyier

DigitalOcean 为您旅程的每个阶段提供云产品。立即开始使用 200 美元的免费额度!

这是一个值得了解的区别。它们看起来非常相似。它们可以做一些相同的事情。但是,一个很容易覆盖,另一个则不容易。

内联样式可能更熟悉一些

<div style="width: 300px; height: 300px;">
  Inline styles on an HTML element.
</div>

SVG 也可以做到这一点

<svg style="width: 300px;">
 Inline styles on an SVG element.
</svg>

但是 SVG 也具有演示属性的概念,这意味着我们可以这样做

<svg width="300px" height="300px">
  Presentational attributes on an SVG element.
</svg>

区别是什么?

演示属性在 CSS 中很容易被覆盖

任何 CSS 都会起作用。

/* These styles will override the presentational attributes */
svg {
  width: 250px;
  height: 250px;
}

内联样式只能被 CSS 中的 !important 样式覆盖

覆盖内联样式的唯一方法是使用 !important 规则

svg {
  width: 250px !important;
  height: 250px !important;
}

一个粗略的图表来强调重点

我发现,这确实会在日常开发中出现。例如,Illustrator 会询问您希望如何设置导出 SVG 的样式

它也 很有道理添加演示属性,尤其是大小属性,到 SVG 以避免 FOUSVG