如何仅用原生CSS高亮每个sectionquestgrp中的首个currentAnswer元素
仅用原生CSS高亮分组内首个指定类元素
需求:在每个.sectionquestgrp分组中,高亮第一个带有.currentAnswer类的元素(比如示例中的数字5和1),无需JavaScript,仅用现代浏览器支持的原生CSS实现。
示例HTML结构
<!-- 第一个分组 --> <div class="sectionquestgrp"> <div class="question"> <span class="option">1</span> <span class="option">2</span> <span class="option currentAnswer">5</span> <!-- 该分组首个需高亮的元素 --> <span class="option currentAnswer">6</span> </div> <div class="question"> <span class="option currentAnswer">7</span> <span class="option">8</span> </div> </div> <!-- 第二个分组 --> <div class="sectionquestgrp"> <div class="question"> <span class="option currentAnswer">1</span> <!-- 该分组首个需高亮的元素 --> <span class="option">2</span> <span class="option">3</span> </div> <div class="question"> <span class="option">4</span> <span class="option currentAnswer">5</span> </div> </div>
实现CSS代码
/* 为所有.currentAnswer元素设置高亮基础样式 */ .sectionquestgrp .currentAnswer { background-color: #ffeb3b; font-weight: bold; padding: 2px 6px; border-radius: 4px; } /* 取消分组内首个.currentAnswer之后的同元素样式,仅保留第一个的高亮 */ .sectionquestgrp .currentAnswer ~ .currentAnswer { background-color: inherit; font-weight: normal; padding: initial; border-radius: initial; }
原理说明
- 先给所有
.sectionquestgrp下的.currentAnswer元素统一设置高亮样式; - 利用相邻兄弟选择器(
~)匹配每个分组中第一个.currentAnswer之后的所有同类型元素,重置其样式,最终仅每个分组内的第一个.currentAnswer会保留高亮效果。
该方案兼容所有现代浏览器(Chrome、Firefox、Safari、Edge),无需依赖任何JavaScript代码。
内容的提问来源于stack exchange,提问作者PPL
相关产品推荐
相关产品推荐

