在展开的 Details 元素上设置背景

Avatar of Chris Coyier
Chris Coyier

DigitalOcean 为您旅程的每个阶段提供云产品。立即开始使用 200 美元的免费额度!

<details> 元素的一个略微有点奇怪的地方是,当它展开时,并不总是 100% 清楚哪些内容在该元素内部,哪些内容不在。我并不是说这总是很重要,或者这是一个特别难以解决的问题,我只是注意到它最近对我来说出现了。

这是一个可视化示例

A screenshot of some text with details elements present. One of them is open. It's not clear what text is within that details and what isn't.
这里哪些文本在 <details> 内部,哪些不在?

解决方案是……CSS。以某种独特的方式为 <details> 设置样式,这样问题就消失了。即使您希望排版保持一致,或者您不希望在 <details> 展开之前进行任何专属样式设置,这也是可能的。使用半透明填充,您甚至可以确保嵌套更深的 <details> 保持清晰。

这是 CSS 代码

details[open] {
  --bg: rgb(0 0 0 / 0.2);
  background: var(--bg);
  outline: 1rem solid var(--bg);
  margin: 0 0 2rem 0;
}

以及演示