You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

鼠标移出div时文本偏移问题求助(附前端代码)

解决鼠标移出div时文本偏移的问题

你实现了鼠标悬停.box-link时切换标题和描述文本的效果,但鼠标移出时文本会向右偏移,怀疑是position: absolute导致的,以下是你的原代码:

原CSS代码

.article-title {
    opacity: 1;
    width: 24%;
    position: absolute;
    padding-bottom: 10px;
    color: #ff0099;
    font-size: 30px;
    transition: all .5s ease-in-out, width 0s linear, absolute 0s linear;
}

.article-desc {
    width: 23%;
    position: absolute;
    opacity: 0;
    transition: all .5s ease-in-out, width 0s linear, absolute 0s linear;
}

.box-link {
    display: flex;
    flex-direction: column;
    padding: 10px;
    border: 2px solid black;
    border-radius: 10px;
    height: 200px;
    width: 25%;
    text-align: center;
    cursor: pointer;
    transition: transform .5s, box-shadow .2s;
}

.box-link:hover {
    transform: scale(1.15);
    box-shadow: 0 0 51px rgba(33, 33, 33, .4);
}

.box-link:hover .article-title {
    width: 89%;
    position: absolute;
    opacity: 0;
}

.box-link:hover .article-desc {
    width: 95%;
    opacity: 1;
}

原HTML代码

<div class="box-link article-1">
    <a class="article-title">The ultimate guide to Australian native flowers</a>
    <a class="article-desc">Looking to add a touch of Australiana when building a bouquet or growing your garden? There are so many stunning Australian native flowers to choose from.</a>
</div>

问题原因

  1. 绝对定位的.article-title和.article-desc没有定位基准:父元素.box-link未设置position: relative,导致这两个元素会相对于视口(而非父容器)定位,位置计算混乱
  2. transition中的absolute 0s linear是无效声明,position属性不支持过渡动画
  3. hover时修改子元素width,但因为没有定位基准,移出后元素位置无法正确回归

修复方案

只需要调整以下几点:

  • 给.box-link添加position: relative,让子元素的绝对定位基于父容器
  • 统一子元素的width为100%,配合父容器的padding实现自适应,避免百分比宽度的偏差
  • 移除无效的transition规则,简化动画逻辑
  • 给绝对定位的子元素添加left: 0,确保始终对齐父容器左侧

修改后的CSS代码

.article-title {
    opacity: 1;
    width: 100%;
    position: absolute;
    left: 0;
    padding: 0 10px 10px; /* 继承父容器的左右padding,保证文本不贴边 */
    color: #ff0099;
    font-size: 30px;
    transition: all .5s ease-in-out;
}

.article-desc {
    width: 100%;
    position: absolute;
    left: 0;
    padding: 0 10px;
    opacity: 0;
    transition: all .5s ease-in-out;
}

.box-link {
    position: relative; /* 关键:添加相对定位作为子元素的定位基准 */
    display: flex;
    flex-direction: column;
    padding: 10px;
    border: 2px solid black;
    border-radius: 10px;
    height: 200px;
    width: 25%;
    text-align: center;
    cursor: pointer;
    transition: transform .5s, box-shadow .2s;
}

.box-link:hover {
    transform: scale(1.15);
    box-shadow: 0 0 51px rgba(33, 33, 33, .4);
}

.box-link:hover .article-title {
    opacity: 0;
}

.box-link:hover .article-desc {
    opacity: 1;
}

说明

HTML代码无需修改,修改后的CSS会保证鼠标移入移出时,文本始终在父容器内正确对齐,不会出现偏移问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 22:33:24