如何为<details>和<summary>标签自定义样式并实现展开动画效果
你代码里的疏漏
::after伪元素默认是行内元素,CSStransform属性对行内元素不生效,这是旋转动画没效果的核心原因- 没有给
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
相关产品推荐
相关产品推荐

