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

使用Clip Path制作六边形切换按钮时遇到的问题

实现选中时显示内层六边形的Clip Path切换按钮

要实现选中状态下显示中间的六边形,你需要在原六边形容器内添加一个独立元素(推荐用伪元素,避免额外HTML结构),通过clip-path定义内层六边形,并在选中状态下控制它的显示。

解决方案代码

如果用自定义类控制状态(适配你原有的.checked类)

.inp_toggle {
  height: 2em;
  width: 2.25em;
  clip-path: polygon(25% 0%, 75% 0%, 100% 50%, 75% 100%, 25% 100%, 0% 50%);
  background: #3c3c3c;
  margin-bottom: 1em;
  position: relative;
  cursor: pointer;
}

.inp_toggle.checked::before {
  content: '';
  position: absolute;
  /* 调整位置和尺寸让内层六边形居中且更小 */
  top: 15%;
  left: 15%;
  width: 70%;
  height: 70%;
  /* 复用六边形路径 */
  clip-path: polygon(25% 0%, 75% 0%, 100% 50%, 75% 100%, 25% 100%, 0% 50%);
  background: #a92800;
}

如果用原生checkbox控制状态(无需JS切换类)

<input type="checkbox" id="hex-toggle" class="inp_toggle">
<label for="hex-toggle"></label>
/* 隐藏原生checkbox */
.inp_toggle {
  position: absolute;
  opacity: 0;
}

/* 外层六边形容器 */
.inp_toggle + label {
  display: block;
  height: 2em;
  width: 2.25em;
  clip-path: polygon(25% 0%, 75% 0%, 100% 50%, 75% 100%, 25% 100%, 0% 50%);
  background: #3c3c3c;
  margin-bottom: 1em;
  position: relative;
  cursor: pointer;
}

/* 选中状态时显示内层六边形 */
.inp_toggle:checked + label::before {
  content: '';
  position: absolute;
  top: 15%;
  left: 15%;
  width: 70%;
  height: 70%;
  clip-path: polygon(25% 0%, 75% 0%, 100% 50%, 75% 100%, 25% 100%, 0% 50%);
  background: #a92800;
}

原理说明

单个元素的clip-path仅能裁剪自身形状,无法同时呈现两个独立的六边形。通过伪元素::before可以在原六边形容器内部生成新的独立元素,利用绝对定位和尺寸比例调整让它居中显示,从而实现选中状态下的双层六边形效果。你可以根据需求调整top/left/width/height的值,改变内层六边形的大小和位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 18:22:46