個別轉換屬性

網頁功能: 個別轉換屬性

transform 屬性可讓您按照指定順序套用多項轉換,但只要變更單一轉換,就必須重新指定整個轉換鏈。因此,為單一轉換建立動畫或轉場效果會變得相當棘手。

個別 CSS 轉換屬性 (translate、rotate 和 scale) 可讓您獨立於 transform 屬性套用轉換。這種做法可簡化覆寫單一轉換的程序,例如在 :hover 上。

重要導入細節

無論 CSS 中的順序為何,個別轉換屬性一律會依固定順序套用:

  1. translate
  2. rotate
  3. scale
  4. transform (最後套用)

如需不同的順序 (例如先縮放「再」旋轉),則必須繼續使用 transform 屬性函式。

轉換函式不會覆寫個別轉換屬性。也就是說,scale: 2; transform: scale(3); 會先縮放 2 倍,再縮放 3 倍,總共 6 倍。

防止堆疊內容和包含區塊發生非預期變更

transform 屬性和個別轉換屬性會影響網頁的版面配置和算繪,並可能導致 z-index 或錨定位置出現非預期行為。強制:如果元素可能在狀態變更 (例如 :hover)、轉場或動畫中套用轉換,請對基本元素套用識別轉換。這可確保套用轉換時,元素的堆疊內容和包含區塊不會變更。

.element{
  /* MANDATORY: Apply identity transformations for properties that will
     change on state changes (like :hover). This prevents unexpected layout
     or z-index shifts caused by creating a new stacking context only on hover. */
  translate: 0px;
  rotate: 0deg;
  scale: 1;
}
.element:hover{
  translate: 10px 10px;
  rotate: 20deg;
  scale: 0.8;
}

獨立動畫和轉場效果

主要優點是能夠定義重疊的動畫或轉場效果,指定不同屬性,而不會發生衝突。

.card {
  /* Define independent animations that don't overwrite each other */
  animation: float 3s infinite ease-in-out;
  
  /* Transition only the scale property for hover states */
  transition: scale 0.3s ease;

  /* Establish the base scale to prevent a sudden stacking context shift when transitioning on hover. */
  scale: 1;
}

.card:hover {
  /* Only the scale changes; the 'float' animation (translate) continues uninterrupted */
  scale: 1.05;
}

@keyframes float {
  0%, 100% { translate: 0 0; }
  50% { translate: 0 -10px; }
}

備用策略

如果瀏覽器不支援個別轉換屬性,請使用傳統的 transform 屬性。請注意,如要修改不同狀態中的某個部分,就必須重新宣告整個轉換堆疊。

.element {
  /* Base transform */
  transform: translate(100px, 0) rotate(45deg);
  /* Specify the identity for the scale property. */
  scale: 1;
}

@supports not (translate: 0px) {
  .element:hover {
    /* Fallback: Must repeat translate and rotate even if only scale changes */
    transform: translate(100px, 0) rotate(45deg) scale(1.1);
  }
}

@supports (translate: 0px) {
  .element:hover {
    /* Modern: Only declare the change */
    scale: 1.1;
  }
}