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

CSS订阅卡片悬停动画异常:右侧卡片触发时其他卡片偏移

定价卡片悬停偏移问题解决方案

问题描述

我在开发订阅组件时,给卡片添加了两个悬停动画效果:

  • 悬停左侧(第一张)卡片时,将其padding-right改为70px实现向左展开,同时给右侧(第三张)卡片加margin-right:35px抵消挤压
  • 悬停右侧(第三张)卡片时,将其padding-left改为70px实现向右展开,同时给左侧(第一张)卡片加margin-left:35px避免其他卡片偏移

但实际测试时,悬停右侧卡片时另外两张卡片仍会偏移,不符合预期效果。


相关代码

父元素样式

.card-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 3px;
}

卡片基础样式

.card {
  padding: 35px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  border-radius: 10px;
  background-color: #BDD2B6;
  transition: 0.3s ease-in-out;
}

动画样式(原错误写法)

.card:nth-child(1):hover {
  padding-right: 70px;
}

.card:nth-child(1):hover~.card:nth-child(3) {
  margin-right: 35px;
}

.card:nth-child(3):hover {
  padding-left: 70px;
}

.card:nth-child(3):hover~.card:nth-child(1) {
  margin-left: 35px;
}

HTML结构

<div class="wrapper">
  <div class="card" id="card-basic">
    <h2>Basic</h2>
    <p class="price" id="title-basic">$19.99</p>
    <hr>
    <p>500 GB Storage</p>
    <hr>
    <p>2 Users Allowed</p>
    <hr>
    <p>Send up to 3 GB</p>
    <hr>
    <button class="btn1">LEARN MORE</button>
  </div>
  <div class="card" id="card-professional">
    <h2>Professional</h2>
    <p class="price" id="title-professional">$24.99</p>
    <hr>
    <p>1 TB Storage</p>
    <hr>
    <p>5 Users Allowed</p>
    <hr>
    <p>Send up to 10 GB</p>
    <hr>
    <button class="btn2">LEARN MORE</button>
  </div>
  <div class="card" id="card-master">
    <h2>Master</h2>
    <p class="price" id="title-master">$39.99</p>
    <hr>
    <p>2 TB Storage</p>
    <hr>
    <p>10 Users Allowed</p>
    <hr>
    <p>Send up to 20 GB</p>
    <hr>
    <button class="btn3">LEARN MORE</button>
  </div>
</div>

问题原因与解决方案

核心问题

  1. CSS的~选择器只能选中当前元素之后的同级元素,所以.card:nth-child(3):hover~.card:nth-child(1)完全无效——第1张卡片在第3张前面,无法反向选中
  2. 原思路通过调整其他卡片margin来抵消挤压,flex布局下容器内元素尺寸联动,这种方式无法精准控制位置

修正后的动画样式

/* 左侧卡片悬停效果:用负margin抵消padding增加的宽度,保持整体布局不变 */
.card:nth-child(1):hover {
  padding-right: 70px;
  margin-left: -35px;
}

/* 右侧卡片悬停效果:同理用负margin抵消宽度变化 */
.card:nth-child(3):hover {
  padding-left: 70px;
  margin-right: -35px;
}

可选优化

如果希望所有卡片在动画过程中完全不被压缩,给卡片添加flex-shrink: 0:

.card {
  /* 原有样式 */
  padding: 35px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  border-radius: 10px;
  background-color: #BDD2B6;
  transition: 0.3s ease-in-out;
  /* 新增:禁止flex容器压缩卡片 */
  flex-shrink: 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 06:20:35