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

如何为<details>和<summary>标签自定义样式并实现展开动画效果

你代码里的疏漏

  • ::after伪元素默认是行内元素,CSS transform属性对行内元素不生效,这是旋转动画没效果的核心原因
  • 没有给summary标签设置弹性布局,自定义箭头无法自动对齐到右侧
  • 直接用content加载外部SVG资源的方式会增加变换控制的复杂度,不建议这么用

正确实现方案

修改后的CSS代码如下,HTML部分无需调整:

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

.thing {
  background-color: cadetblue;
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.new_game {
  font-size: 3rem;
}

.what_is_question {
  background-color: cornflowerblue;
  cursor: pointer;
  font-size: 5rem;
}

.what_is_question[open] {
  background-color: darkmagenta;
}

/* 给summary加flex布局实现文字和箭头左右对齐 */
.question_title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  list-style: none; /* 兼容低版本浏览器,避免默认标记残留 */
}

/* 双写法移除默认标记,兼容所有主流浏览器 */
.question_title::marker {
  content: none;
}
.question_title::-webkit-details-marker {
  display: none;
}

/* 自定义箭头,设置为行内块级元素支持transform */
.question_title::after {
  content: "";
  width: 24px;
  height: 24px;
  /* 用背景图加载箭头SVG,方便控制尺寸和显示效果 */
  background: url(./images/expand_more_black_24dp.svg) center / contain no-repeat;
  display: inline-block;
  /* 添加过渡属性实现平滑旋转动画 */
  transition: transform 0.3s ease;
}

/* details展开时旋转箭头 */
.what_is_question[open] .question_title::after {
  transform: rotate(180deg);
}

.answer {
  background-color: darkkhaki;
  font-size: 3rem;
  padding-left: 3.5%;
}

如果想要用字体图标实现箭头,只需要把::after里的背景图相关代码删掉,换成对应字体图标的content编码,设置好字体属性即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 11:27:03