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

如何基于选项选中状态为关闭的CSS下拉框添加轮廓

实现下拉框关闭且有选中项时显示轮廓

要达成你要的效果,核心是利用CSS :has() 选择器结合Tailwind的状态类,同时检测「下拉框关闭」和「存在选中选项」两个状态,具体实现如下:

修改后的代码

<script src="https://cdn.tailwindcss.com/3.4.3"></script>

<main class="w-full max-w-xl mx-auto">
  <h1 class="text-3xl mt-12">Multi-Select Dropdown</h1>
  <div class="flex flex-col">
    <!-- 给外层label添加自定义样式规则 -->
    <label class="relative [&:has(input[name='countries2']:checked)_:not(.peer:checked)_>div]:outline-2 [&:has(input[name='countries2']:checked)_:not(.peer:checked)_>div]:outline-blue-500">
      <input type="checkbox" class="peer hidden" />
      <div class="inline-flex cursor-pointer rounded border px-5 py-2 after:ml-1 after:inline-flex after:items-center after:text-xs after:transition-transform after:content-['▼'] peer-checked:after:-rotate-180">
        Select one or more countries
      </div>
      <div class="pointer-events-none absolute z-10 max-h-60 w-full overflow-y-scroll border bg-red-300 opacity-0 transition-opacity peer-checked:pointer-events-auto peer-checked:opacity-100">
        <ul>
          <li>
            <label class="[&:has(input:checked)]:bg-blue-200 flex cursor-pointer whitespace-nowrap px-2 py-1 transition-colors hover:bg-blue-100">
              <input type="checkbox" class="cursor-pointer" name="countries2" value="Spain" />
              <span class="ml-1">Spain</span>
            </label>
          </li>
          <li>
            <label class="[&:has(input:checked)]:bg-blue-200 flex cursor-pointer whitespace-nowrap px-2 py-1 transition-colors hover:bg-blue-100">
              <input type="checkbox" class="cursor-pointer" name="countries2" value="France" />
              <span class="ml-1">France</span>
            </label>
          </li>
        </ul>
      </div>
    </label>
  </div>
</main>

关键逻辑说明

给外层label添加的自定义Tailwind类:

[&:has(input[name='countries2']:checked)_:not(.peer:checked)_>div]:outline-2 [&:has(input[name='countries2']:checked)_:not(.peer:checked)_>div]:outline-blue-500
  • &:has(input[name='countries2']:checked):检测当前label内是否有选中的选项复选框
  • _:not(.peer:checked):匹配未被选中的下拉控制复选框(即下拉框处于关闭状态)
  • _>div:定位到触发下拉的文本容器
  • :outline-2 :outline-blue-500:给目标容器添加2px宽的蓝色轮廓

这种写法不需要额外调整DOM结构,直接通过Tailwind的自定义语法实现状态组合检测,完美契合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 23:17:33