萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS Transform 旋轉 DIV 元素完整教學 (含 IE Matrix 回退)

標準寫法 (現代瀏覽器)

.rotate-40 {
  transform: rotate(40deg);
  transform-origin: center center; /* 旋轉中心,預設即中心 */
}

瀏覽器前綴 (舊版本兼容)

.rotate-40 {
  -webkit-transform: rotate(40deg);
  -moz-transform: rotate(40deg);
  -o-transform: rotate(40deg);
  -ms-transform: rotate(40deg);
  transform: rotate(40deg);
}

IE 6-8 Matrix 濾鏤回退

IE9 以下不支援 transform,需用 filter:progid:DXImageTransform.Microsoft.Matrix。需計算旋轉矩陣:

<!--[if lte IE 8]>
<style>
.rotate-40 {
  filter: progid:DXImageTransform.Microsoft.Matrix(
    sizingMethod='auto expand',
    M11=0.76604444, M12=-0.64278761,
    M21=0.64278761, M22=0.76604444
  ); /* cos40°, -sin40°, sin40°, cos40° */
  /* IE6/7 需額外設定 left/top 修正位移 */
}
</style>
<![endif]-->

矩陣計算:M11=cosθ, M12=-sinθ, M21=sinθ, M22=cosθ。角度採**弧度**或直接用線上工具 (如 Matrix Filter Calculator) 產生。

完整範例

<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>DIV 旋轉</title>
<style>
#box {
  width:200px; height:100px; background:#09f; color:#fff;
  font:bold 24px/100px Arial; text-align:center;
  position:absolute; left:100px; top:100px;
  transform:rotate(40deg);
  -webkit-transform:rotate(40deg);
  -moz-transform:rotate(40deg);
  -ms-transform:rotate(40deg);
  -o-transform:rotate(40deg);
}
<!--[if lte IE 8]>
<style>
#box {
  filter:progid:DXImageTransform.Microsoft.Matrix(sizingMethod='auto expand', M11=0.76604444, M12=-0.64278761, M21=0.64278761, M22=0.76604444);
  left:50px; top:50px; /* 手動微調 */
}
</style>
<![endif]-->
</style></head><body>
<div id="box">旋轉 40°</div></body></html>

注意事項

  • transform 不影響文件流佈局,旋轉後仍佔原空間;若需重排,配合 margin 或改用 position:absolute。
  • transform-origin 可改變旋轉中心 (如 0 0 左上角)。
  • 3D 旋轉用 rotateX/Y/Z 或 rotate3d,需 transform-style:preserve-3d。
  • 動畫:@keyframes spin {to{transform:rotate(360deg)}} + animation:spin 2s linear infinite。
copyright © 萬盛學電腦網 all rights reserved