如何通过ID为同class的不同div设置对应背景色?
实现同class不同id元素的背景色匹配对应ID的文字颜色
你想要让每个带.thing类的div,其背景色等于自身ID选择器中定义的color值。纯CSS无法直接“读取”其他规则的属性值,但可以通过以下两种方案实现需求:
方法1:使用CSS自定义属性(推荐)
这种方式在纯CSS内即可完成属性关联,维护性高:
HTML代码
<div class="thing" id="one">内容1</div> <div class="thing" id="two">内容2</div> <div class="thing" id="three">内容3</div>
CSS代码
#one { --text-color: green; color: var(--text-color); } #two { --text-color: red; color: var(--text-color); } #three { --text-color: blue; color: var(--text-color); } .thing { background-color: var(--text-color); /* 可选样式:提升视觉效果 */ padding: 10px; margin: 6px 0; color: white; /* 避免文字与背景色混淆 */ }
原理:给每个ID定义一个自定义属性--text-color,让ID的color和.thing的background-color都引用这个变量,修改变量值就能同步更新两个属性。
方法2:JavaScript方案(兼容旧浏览器)
如果需要兼容不支持CSS变量的浏览器(如IE),可以用JS动态同步颜色:
JavaScript代码
const thingElements = document.querySelectorAll('.thing'); thingElements.forEach(el => { const computedColor = getComputedStyle(el).color; el.style.backgroundColor = computedColor; });
原理:通过getComputedStyle获取元素实际生效的文字颜色,再将该值赋值给元素的背景色属性。
内容的提问来源于stack exchange,提问作者OstryJR
相关产品推荐
相关产品推荐

