首先说明,此处的 transform属性 是指 CSS transform property, 而非 SVG元素上 transform attribute.css
CSS中的transform属性在应用到SVG中的元素时要特别注意,由于此时transform相关属性的默认值以及某些取值的含义和html元素有很大区别, 而这种区别,通常的介绍文档(例如MDN上的文档)并不会特别说起,只有标准文档中才有具体的说明(https://drafts.csswg.org/css-transforms/#transform-property)。html
CSS transform 属性应用到 svg 元素上时和应用到 html 上时,主要有如下几点区别:svg
transform-origin 的默认值不一样: 对于html元素,其默认值为 50% 50%, 而对于 svg 元素, 其默认值为 0 0,更精确的解释是:
For SVG elements without associated CSS layout box the initial used value is 0 0 as if the user agent style sheet contained:
*:not(svg), *:not(foreignObject) > svg {
transform-origin: 0 0;
}rest
transform-box 的取值以及含义不一样 transform-box 有3中取值: border-box | fill-box | view-box , 通常 html元素只会取前两种值,而svg能够取第三个值 view-box。 两种元素的默认值都是border-box,可是border-box 对于 html元素 和 svg元素的意义并不相同。
对于 html 元素, border-box 就表示 Uses the border box as reference box;
而对于svg元素: For SVG elements without an associated CSS layout box, the used value for border-box is view-box, 而 view-box的含义是:code
Uses the nearest SVG viewport as reference box. If a viewBox attribute is specified for the SVG viewport creating element: The reference box is positioned at the origin of the coordinate system established by the viewBox attribute. The dimension of the reference box is set to the width and height values of the viewBox attribute.
归纳的说,默认状况下:
对于html元素来讲,transform 属性参考的坐标系是该元素本身的border-box所在的位置的左上角做为原点,transform相关属性中percentage 值相对的目标也是该元素的border-box的宽和高;
而对于 svg 元素来讲,transform 属性参考的坐标系是其最近的 svg 视口,transform相关属性中percentage 值相对的也是响应的viewport的宽和高。
这种区别,实际上是合理的,由于这样对于 svg来讲, CSS transform property 就是和 svg 元素的 transform attribute的行为一致了。而 html文档中,一般并不像svg那样,有画布和视口的概念(html中通常也用不上这两个概念),因此transform 属性参考的就是该元素自己所在的位置以及它原本的尺寸。orm
若是针对一个svg元素同时定义了上述两个属性,CSS transform 属性的优先级更高。htm