如何在<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
相关产品推荐
相关产品推荐

