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

求助:仅用CSS实现标签页点击后保持白色状态

实现点击后保持激活状态的纯CSS标签页

要实现点击标签后保持白色状态,你可以利用CSS的:has()和:target伪类来完成,无需JavaScript。以下是修改后的代码:

修改后的CSS代码

body {
  font-family:"Open Sans";
  background:white;
  height:300px;
  font-size:14px;
}

.tab section {
  display:none;
}

.tab section:target, .tab section:last-of-type {
  display:block;
}

.tab section:target~section {
  display:none;
}

.L1 {
  padding:17px 10px;
  border:1px solid #2c3e50;
  color:white !important;
  margin-left:-1px;
  text-decoration: none; /* 去掉默认链接下划线 */
}

.L1:hover {
  background-color:white;
  color:black !important;
  border-bottom:1px solid white;
}

/* 点击激活后的样式 */
.tab:has(section#tab1:target) a[href="#tab1"],
.tab:has(section#tab2:target) a[href="#tab2"],
.tab:has(section#tab3:target) a[href="#tab3"],
/* 默认激活最后一个tab(tab1)的样式 */
.tab a[href="#tab1"] {
  background-color:white;
  color:black !important;
  border-bottom:1px solid white;
}

对应的HTML代码(无需修改)

<section class="tab" style="border:none;background:#1abc9c;max-width:46.5rem;width:100%;margin:5px auto;height:51px;line-height:51px;">
  <a class="L1" href="#tab1">tab1</a>
  <a class="L1" href="#tab2" style="margin-left:-5px;">tab2</a>
  <a class="L1" href="#tab3" style="margin-left:-5px;">tab3</a>
  <section id="tab2" style="margin-top:-60px !important;padding-top:61px;">
        <span>hello2</span>
   </section>
   <section id="tab3" style="margin-top:-60px !important;padding-top:61px;">
        <span>hello3</span>
   </section>
   <section id="tab1" style="margin-top:-60px !important;padding-top:61px;">
    <span>hello1</span>
  </section>
</section>

实现原理

  1. :target伪类:当URL的hash值与section的id匹配时,该section会被标记为:target,以此判断哪个标签页被激活。
  2. :has()伪类:检测.tab容器内是否存在处于:target状态的section,给对应href匹配的a标签添加激活样式。
  3. 默认激活样式:因为原代码默认显示最后一个section(tab1),所以给对应的a标签添加默认激活样式,保证初始状态的一致性。

注意::has()伪类已被现代主流浏览器支持,若需兼容旧版浏览器,可调整HTML结构将a标签放入对应section内部,通过相邻兄弟选择器实现,但会增加结构复杂度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 11:26:52