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

嵌套div后,如何通过CSS单选按钮实现内容显示/隐藏?

解决单选按钮嵌套div后CSS显示/隐藏失效的问题

问题根源

原代码中的~(通用兄弟选择器)只能选中同一个父元素下的后续兄弟元素。当你把单选按钮嵌套进.myRadioStyle div后,单选按钮和内容div#contentDescription/#contentShipping不再属于同一层级,原选择器无法关联到目标内容,导致功能失效。

解决方案一:使用:has()伪类(推荐,结构改动最小)

:has()伪类可以检测父容器是否包含满足条件的子元素,通过#radioGroup这个父容器来关联外部的内容div,无需调整原有HTML结构。

修改后的CSS代码:

#radioGroup:has(#input_description:checked) ~ #contentDescription,
#radioGroup:has(#input_shipping:checked) ~ #contentShipping {
    display: block;
}

#contentDescription, #contentShipping{
  display: none;
}

.radio_item_menu:checked + .label_item_menu {
  font-weight: bold;
}

解决方案二:调整HTML结构兼容旧浏览器

如果需要兼容不支持:has()的旧版本浏览器,可以将内容div移动到#radioGroup容器内,让它们成为.myRadioStyle的兄弟元素,这样就能继续使用~选择器:

修改后的HTML

<div id="radioGroup">
  <div class="myRadioStyle">
    <input type="radio" name="navbar_menu_store" id="input_description" class="radio_item_menu">
    <label for="input_description" class="label_item_menu">Description</label>
  </div>
  <div class="myRadioStyle">
    <input type="radio" name="navbar_menu_store" id="input_shipping" class="radio_item_menu">
    <label for="input_shipping" class="label_item_menu">Shipping</label>
  </div>

  <div id="contentDescription"><p class="testo_scheda">
  This is some text</p>
  </div>

  <div id="contentShipping"><p class="testo_scheda">
  This is some other text</p>
  </div>
</div>

对应CSS(无需大幅修改)

#input_description:checked ~ #contentDescription,
#input_shipping:checked ~ #contentShipping {
    display: block;
}

#contentDescription, #contentShipping{
  display: none;
}

.radio_item_menu:checked + .label_item_menu {
  font-weight: bold;
}

选择器说明

  • ~:通用兄弟选择器,匹配当前元素之后所有同层级的兄弟元素。
  • +:相邻兄弟选择器,匹配当前元素之后第一个同层级的兄弟元素。
  • :has():父选择器,匹配包含指定子元素的父容器,目前Chrome、Firefox 121+、Safari等主流浏览器均已支持。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 22:23:19