You need to enable JavaScript to run this app. CSS transform: scale()无法从中心缩放 悬停时logo上移求助
优惠活动
大模型
产品
解决方案
定价
更多

CSS transform: scale()无法从中心缩放 悬停时logo上移求助

问题根因

你遇到的偏移问题和transform-origin完全无关,核心是几个细节错配:

  • 两个交互状态下的垂直方向平移值不一致:非悬停时img用的是translate(-50%,-35%),悬停时直接把垂直平移改成了translate(-50%,-50%),相当于缩放的同时额外把图片向上拉了一段距离,自然会出现上移的效果。
  • 原CSS存在写法疏漏:类选择器.portfolio-projects漏了前缀.,且该规则块没有闭合大括号,会连带影响后续.project样式的正常解析。
  • 原transition仅写了时长参数,没有指定过渡属性,默认会触发所有可过渡属性的动画,放大了位置偏移的观感。
修正实现

如果要实现悬停时仅缩放、位置不偏移,只要保证两个状态下的transform里,平移部分的数值完全一致,只修改scale值即可,完整可运行的CSS如下:

.portfolio-projects {
    display: grid;
    grid-gap: 50px;
    margin: 50px 0;
    max-width: 1050px;
}

.project {
    position: relative;
    cursor: pointer;
    background-color: #ccc;
    max-width: 500px;
    height: 325px;
    overflow: hidden;
}

.project img {
    position: absolute;
    /* 保留你原本想让图片偏上的初始布局 */
    top: 35%;
    left: 50%;
    transform: translate(-50%, -35%) scale(0.8);
    /* 明确指定过渡的是transform属性,减少不必要的性能消耗 */
    transition: transform 0.2s ease;
}

.project:hover img {
    /* 平移值和非悬停状态完全一致,只修改缩放比例 */
    transform: translate(-50%, -35%) scale(0.9);
}
注意点
  • transform的函数是按顺序执行的,只要两个状态的平移参数完全相同,不管scale的数值怎么调整,图片的基准锚点都不会偏移,自然不会出现莫名上移的问题。
  • 不需要额外设置transform-origin: center,因为这个值本身就是所有元素的transform-origin默认值,单独设置也解决不了参数错配导致的偏移。

内容的提问来源于stack exchange,提问作者supernova

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.29 14:54:06