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

如何在<details>折叠时仍显示内容并根据open属性设置差异化样式

问题根源

浏览器原生默认样式会自动隐藏<details>折叠状态下除<summary>之外的所有子元素,所以你原本写的样式不生效,核心需要先覆盖这个默认隐藏逻辑。

完整实现代码

CSS代码

/* 覆盖原生默认隐藏规则,让折叠时非summary内容也可展示 */
details:not([open]) :not(summary) {
  display: block;
  margin: 0;
}

details[open] p {
  flex-grow: 1;
  max-height: unset;
  overflow: visible;
  text-overflow: unset;
}

details:not([open]) p {
  max-height: 3em;
  overflow: hidden;
  text-overflow: ellipsis;
  /* 多行文本省略适配,可通过-webkit-line-clamp调整展示行数 */
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

HTML代码

<details>
  <summary>This is the summary element.</summary>
  <p>This is the details element.</p>
</details>

效果说明

折叠状态下<p>标签内容会展示指定行数,超出部分自动显示省略号;展开后自动适配高度展示全部内容,完全符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 02:06:04