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

height:0; overflow:hidden; 与padding冲突导致自定义下拉选择器无法隐藏

自定义下拉选择器平滑动画问题解决

问题核心

  1. 默认盒模型(content-box)下,height:0时元素的实际高度会包含上下padding,导致.select-body实际高度为27px+31px=58px,overflow:hidden无法完全隐藏内容。
  2. CSS过渡不支持从具体数值到auto的动画,设置height:auto时不会出现平滑效果。

最优解决方案

用max-height替代height控制展开收起,将padding和背景色转移到内部容器,既解决padding导致的内容泄露,又能实现平滑过渡。

修改后的HTML代码

<div class="select accordion">
  <div class="select-header">
    <span class="select-current">City</span>
    <div class="select-icon"></div>
  </div>
  <div class="select-body">
    <div class="select-content">
      <div class="select-item">Canandaigua, NY</div>
      <div class="select-item">New York City</div>
      <div class="select-item">Yonkers, NY</div>
      <div class="select-item">Sherrill, NY</div>
    </div>
  </div>
</div>

修改后的CSS代码

.select-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 50px;
  padding: 0 35px 0 20px;
  background-color: #D6E7D2;
  cursor: pointer;
  transition: background 0.5s;
}

.select-body {
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.5s ease;
}

.select.active .select-body {
  max-height: 500px; /* 设置足够大的值,超过内容实际高度即可 */
}

.select-content {
  padding-top: 27px;
  padding-left: 20px;
  padding-bottom: 31px;
  background-color: #DCE9D9;
}

.select-item {
  line-height: 35px;
  cursor: pointer;
  color: #499A18;
}

.select-item:not(:last-child) {
  padding-bottom: 12px;
}

方案说明

  • 将.select-body的padding和背景色移到内部的.select-content中,让.select-body仅作为控制展开收起的容器,避免padding影响容器高度。
  • 使用max-height:0隐藏,激活时设置一个足够大的max-height(如500px),CSS可以对max-height进行平滑过渡,适配不同数量的下拉选项,无需计算精确高度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 08:10:23