如何为summary::after背景SVG标记设置CSS变量颜色?
解决::after中SVG图标颜色无法通过CSS变量控制的问题
你尝试通过<summary>::after的background加载SVG作为自定义标记,想要用CSS变量var(--fontColor)控制颜色,但设置color属性无效。以下是问题原因和解决方法:
问题根源
当SVG作为background-image的data URI使用时,SVG内部的currentColor无法继承伪元素的color值——因为背景图属于独立的渲染上下文,不会继承宿主元素的颜色属性,所以你设置的color: var(--fontColor)对SVG无效。
解决方案
直接将CSS变量嵌入SVG的fill属性中,同时对变量值进行URL编码(因为data URI要求特殊字符转义)。
修改后的CSS代码
details { display: flex; } details summary { cursor: pointer; } summary { display: flex; list-style-position: outside; align-items: center; justify-content: space-between; margin-left: 0; padding: 0; } summary::-webkit-details-marker { display: none; } summary::after { content: ""; width: 18px; height: 18px; /* 直接将CSS变量嵌入SVG的fill属性,注意转义特殊字符 */ background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='%7B--fontColor%7D' class='bi bi-caret-down-fill' viewBox='0 0 16 16'%3E%3Cpath d='M7.247 11.14 2.451 5.658C1.885 5.013 2.345 4 3.204 4h9.592a1 1 0 0 1 .753 1.659l-4.796 5.48a1 1 0 0 1-1.506 0z' /%3E%3C/svg%3E"); background-size: cover; transition: 0.2s; } details[open] > summary::after { transform: rotate(180deg); }
关键修改说明
- 移除了无效的
color: var(--fontColor)声明 - 将SVG内部的
fill='currentColor'替换为fill='%7B--fontColor%7D':%7B是{的URL编码,%7D是}的URL编码- 如果你的
--fontColor变量是不带#的十六进制值(比如fff),需要改成fill='%23%7B--fontColor%7D';如果变量已经包含#(比如#ffffff),则保持fill='%7B--fontColor%7D'即可
这样SVG的填充色就会直接读取CSS变量--fontColor的值,完美适配主题切换。
内容的提问来源于stack exchange,提问作者ptrrdrck
相关产品推荐
相关产品推荐

