CSS 中的 translateY() 函数用于沿 Y 轴垂直平移或移动元素。它是 CSS 中的转换函数之一,允许您修改网页上元素的位置和外观。结果是 <transform-function> 数据类型。
translateY() 函数通常与其他 CSS 转换函数结合使用,如 translateX()(用于水平移动)、scale()(用于缩放)和 rotate()(用于旋转),以在 Web 元素上创建更复杂的转换和动画。
可能的值
函数 translateY() 只能接受一个参数。它指定了元素应垂直移动的距离。正值将元素向下移动,而负值将其向上移动。
- <length-percentage>:可以是 <length> 或 <percentage> 值,表示平移向量 [0,ty] 的垂直 y 分量。
语法
transform: translateY(100px) | translateY(45%);
CSS translateY() - 长度值
以下是以长度值作为参数的 translateY() 函数示例:
<html>
<head>
<style>
div {
height: 100px;
width: 100px;
border: 2px solid black;
background-color: aquamarine;
margin-bottom: 5px;
}
.translate-y-length {
transform: translateY(100px);
background-color: tomato;
}
</style>
</head>
<body>
<div>No translateY() applied</div>
<div class="translate-y-length">translateY(100px) applied</div>
</body>
</html>
CSS translateY() - 百分比值
以下是以百分比值作为参数的 translateX() 函数示例:
<html>
<head>
<style>
div {
height: 110px;
width: 110px;
border: 2px solid black;
background-color: aquamarine;
margin-bottom: 5px;
}
.translate-y-percent {
transform: translateY(30%);
background-color: tomato;
}
</style>
</head>
<body>
<div>No translateY() applied</div>
<div class="translate-y-percent">translateY(30%) applied</div>
</body>
</html>
CSS translateY() - 负百分比值
以下是使用负百分比值作为参数的 translateY() 函数示例:
<html>
<head>
<style>
div {
height: 110px;
width: 110px;
border: 2px solid black;
background-color: aquamarine;
margin-bottom: 5px;
}
.translate-y-percent {
transform: translateY(-20%);
background-color: tomato;
}
</style>
</head>
<body>
<div>No translateY() applied</div>
<div class="translate-y-percent">translateY(-20%) applied</div>
</body>
</html>
CSS translateY() - 负长度值
以下是使用负长度值作为参数的 translateY() 函数示例:
<html>
<head>
<style>
div {
height: 115px;
width: 115px;
border: 2px solid black;
background-color: aquamarine;
margin-bottom: 5px;
}
.translate-y-length {
transform: translateY(-10px);
background-color: tomato;
}
</style>
</head>
<body>
<div>No translateY() applied</div>
<div class="translate-y-length">translateY(-10px) applied</div>
</body>
</html>