transform属性和svg元素

首先说明,此处的 transform属性 是指 CSS transform property, 而非 SVG元素上 transform attribute.

CSS中的transform属性在应用到SVG中的元素时要特别注意,因为此时transform相关属性的默认值以及某些取值的含义和html元素有很大区别, 而这种区别,一般的介绍文档(例如MDN上的文档)并不会特别提及,只有标准文档中才有具体的说明(https://drafts.csswg.org/css-transforms/#transform-property)。

CSS transform 属性应用到 svg 元素上时和应用到 html 上时,主要有以下几点区别:

  1. 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;
    }

  2. 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的含义是:

     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 属性参考的就是该元素本身所在的位置以及它本来的尺寸。

CSS transform 属性和 svg transform attribute 的优先级

如果针对一个svg元素同时定义了上述两个属性,CSS transform 属性的优先级更高。

posted on 2018-03-14 08:51  等待未知  阅读(358)  评论(0编辑  收藏  举报

导航