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

CSS :target选择器失效:点击后.answer元素max-height不生效

解决折叠面板:target选择器不生效的问题

我来帮你排查下这个折叠面板的样式问题,你遇到的.answer元素max-height没变化的情况,大概率是以下几个原因之一,我们一步步来解决:

1. 缺少.answer的初始隐藏样式

要实现折叠展开的效果,首先得给.answer设置初始的max-height: 0和overflow: hidden,否则即使:target触发了,也看不出高度变化。你需要补充基础样式:

.answer {
  max-height: 0;
  overflow: hidden;
  /* 可选:添加过渡动画让展开/收起更平滑 */
  transition: max-height 0.3s ease-in-out;
}

.accordion-item:target .answer {
  max-height: 20rem;
}

2. CSS选择器优先级冲突

如果你的代码里有其他针对.answer的样式规则,优先级比.accordion-item:target .answer高的话,就会覆盖这个设置。比如:

  • 直接写.answer { max-height: 0 !important; }
  • 更具体的选择器比如.accordion-container .answer

解决办法:

  • 提高目标选择器的优先级,比如改成.accordion-item:target > .answer(如果.answer是.accordion-item的直接子元素)
  • 检查并移除冲突样式里的!important(尽量避免用!important,会增加后续维护难度)
  • 把你的:target样式放在所有.answer相关样式的后面(CSS中后定义的规则会覆盖前面的同优先级规则)

3. 页面中存在重复的ID

:target选择器是匹配当前URL锚点对应的第一个拥有该ID的元素,如果你的页面里有多个id="question1"的元素,点击后只会匹配第一个,其他元素的.answer不会生效。

解决办法:确保每个.accordion-item的ID都是唯一的,比如question1、question2这样依次命名。

完整可运行示例

这里给你一个完整的测试代码,你可以直接复制运行验证效果:

<div class="accordion-item" id="question1">
  <a class="accordion-link" href="#question1">
    What is COVID-19?
    <ion-icon class="ion" name="add-outline"></ion-icon>
    <ion-icon class="ion" name="remove-outline"></ion-icon>
  </a>
  <div class="answer">
    <p>
      COVID-19 is the infectious disease caused by the most recently discovered coronavirus. This new virus and disease were unknown before the outbreak began in Wuhan, China, in December 2019.
    </p>
  </div>
</div>

<style>
.accordion-link {
  display: block;
  padding: 1rem;
  background: #f5f5f5;
  text-decoration: none;
  color: #333;
  position: relative;
}

.ion {
  position: absolute;
  right: 1rem;
  top: 50%;
  transform: translateY(-50%);
}
/* 切换图标显示状态,点击后隐藏加号显示减号 */
.accordion-item:not(:target) .ion[name="remove-outline"],
.accordion-item:target .ion[name="add-outline"] {
  display: none;
}

.answer {
  max-height: 0;
  overflow: hidden;
  padding: 0 1rem;
  transition: max-height 0.3s ease;
  background: #fff;
}

.accordion-item:target .answer {
  max-height: 20rem;
  padding: 1rem;
}
</style>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 00:32:37