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

checkbox选中/取消控制div带过渡展开收起,取消时过渡失效问题求助

问题根因

你遇到的收起无过渡的视觉效果,本质原因是 background-image 属性本身不支持CSS过渡:

  • 你只在checkbox选中的状态下给.navigation__background设置了background-image,未选中时默认是background-image: unset
  • 取消选中的瞬间,背景图会直接消失,哪怕width的过渡正在执行,没有背景的元素你也看不到收缩过程,视觉上就像直接消失了。

另外你代码里rgba(red, .8)的写法不符合CSS规范,rgba参数需要传入数值格式的色值,也建议同步修正。

解决方法

直接把渐变背景写在.navigation__background的默认样式中即可,width: 0时元素宽度为0,背景不会透出,不会影响默认状态的显示,这样收缩过程中背景一直存在,就能看到完整的宽度过渡效果。

修改后的CSS代码如下:

.navigation {
  background-color: rgba(255, 0, 0, .8);
  float: left;
  width: 100vw;
  z-index: 2000;
  transition: .5s ease-in-out;
}

.navigation__checkbox {
  z-index: 2500;
}
.navigation__background {
  height: 100vh;
  width: 0;
  right: 0;
  top: 0;
  position: fixed;
  background-image: linear-gradient(blue, gray); /* 背景移到默认样式 */
  z-index: 1000;
  transition: width .3s ease-in-out;
}

 
.navigation__checkbox:checked ~ .navigation__background {
  width: 90%;
}

如果希望收起时更自然,也可以新增opacity过渡做优化,写法如下:

.navigation__background {
  height: 100vh;
  width: 0;
  right: 0;
  top: 0;
  position: fixed;
  background-image: linear-gradient(blue, gray);
  z-index: 1000;
  transition: width .3s ease-in-out, opacity .2s ease-in-out; /* 新增透明度过渡 */
  opacity: 0; /* 默认透明 */
}

.navigation__checkbox:checked ~ .navigation__background {
  width: 90%;
  opacity: 1; /* 选中时完全显示 */
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 20:36:03