transform屬性和svg元素

首先說明,此處的 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

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

  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的含義是: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

CSS transform 屬性和 svg transform attribute 的優先級

若是針對一個svg元素同時定義了上述兩個屬性,CSS transform 屬性的優先級更高。htm

相關文章
相關標籤/搜索