translate() 讓元素沿水平方向(X 軸)與垂直方向(Y 軸)移動。
共有三種形式:
(1)translateX(x):僅水平方向移動;
(2)translateY(y):僅垂直方向移動;
(3)translate(x,y):水平與垂直方向同時移動。
語法:
transform:translateX(x);
說明:
CSS3 中所有變形方法都屬於 transform 屬性,因此每個方法前面都要加上「transform:」。這點務必記牢。
x 為元素在水平方向的移動距離,單位可用 px、em 或百分比。x 為正時向右移動,為負時向左移動。
舉例:
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>CSS3位移translate()方法</title>
<style type="text/css">
/*設置原始元素樣式*/
#origin {
margin:100px auto;
/*水平居中*/
width:200px;
height:100px;
border:1px dashed silver;
}
/*設置當前元素樣式*/
#current {
width:200px;
height:100px;
color:white;
background-color: #3EDFF4;
text-align:center;
transform:translateX(20px);
-webkit-transform:translateX(20px);
/*兼容-webkit-引擎浏覽器*/
-moz-transform:translateX(20px);
/*兼容-moz-引擎浏覽器*/
}
</style>
</head>
<body>
<div id="origin">
<div id="current"></div>
</div>
</body>
</html>
分析:
「transform:translateX(20px);」表示元素向右位移 20px。若把 20px 改成 -20px,元素便改為向左位移 20px。
語法:
transform:translateY(y)
說明:
y 為元素在垂直方向的移動距離,單位可用 px、em 或百分比。y 為正時向下移動,為負時向上移動。
看到這裡很多人會疑惑:照理說 y 為正應該向上、為負應該向下才對?
這裡要說清楚:CSS 採用的是「左上角為原點、Y 軸正方向朝下」的座標系,因為螢幕內容本身就是由上而下閱讀的。你想到的那一套「Y 軸向上為正」是數學形式的座標系,適用場景不同。這兩個系統經常被混用,务必先確認自己身在何處。
舉例:
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>CSS3位移translate()方法</title>
<style type="text/css">
/*設置原始元素樣式*/
#origin {
margin:100px auto;
/*水平居中*/
width:200px;
height:100px;
border:1px dashed silver;
}
/*設置當前元素樣式*/
#current {
width:200px;
height:100px;
color:white;
background-color: #3EDFF4;
text-align:center;
transform:translateY(20px);
-webkit-transform:translateY(20px);
/*兼容-webkit-引擎浏覽器*/
-moz-transform:translateY(20px);
/*兼容-moz-引擎浏覽器*/
}
</style>
</head>
<body>
<div id="origin">
<div id="current"></div>
</div>
</body>
</html>
分析:
把 20px 改成 -20px,元素就改為向上位移 20px,可以自行驗證。
語法:
transform:translate(x,y)
說明:
x 為水平方向距離,y 為垂直方向距離。y 為選填參數,若省略則元素僅沿 X 軸移動。
舉例:
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>CSS3位移translate()方法</title>
<style type="text/css">
/*設置原始元素樣式*/
#origin {
margin:100px auto;
/*水平居中*/
width:200px;
height:100px;
border:1px dashed silver;
}
/*設置當前元素樣式*/
#current {
width:200px;
height:100px;
color:white;
background-color: #3EDFF4;
text-align:center;
transform:translate(20px,40px);
-webkit-transform:translate(20px,40px);
/*兼容-webkit-引擎浏覽器*/
-moz-transform:translate(20px,40px);
/*兼容-moz-引擎浏覽器*/
}
</style>
</head>
<body>
<div id="origin">
<div id="current"></div>
</div>
</body>
</html>
分析:
單純讓元素位移其實實用價值有限,translate() 真正的舞台是搭配 CSS3 動畫,做出進場、滑動、懸浮等動態效果。
同樣的位移效果也能用 jQuery 的 animate() 實作,但 jQuery 有一個前置條件:被移動的元素必須先設定 position 屬性,否則 animate() 不會生效。CSS3 的 translate() 沒有這個負擔,程式碼更乾淨,效能也更好。