【问题标题】:Aunt/Uncle selector in CSS? [closed]CSS 中的阿姨/叔叔选择器? [关闭]
【发布时间】:2023-02-23 21:46:38
【问题描述】:

我目前有这个 html 布局

如何根据 input[type="radio"] 选择“Menu Display Focus”div 中的图像,例如,当我检查第一个输入时,我只能选择第一个图像?

我试图在互联网上查找此类问题,但大多数将 imgs 作为输入的子项或直接与其相邻,是否没有像我描述的那样选择的方法?

【问题讨论】:

  • 通常,CSS 只能沿着文档树往上走,而不能回到根部。
  • 请分享代码 sn-p
  • 请将您的 HTML 的最小结构发布为文本,而不是图像。
  • “但大多数人会让 imgs 成为输入的孩子”-一开始是不可能的;输入字段没有孩子们.
  • HTML 是否是这个结构,还是你可以修改它?如果您能够将单选按钮本身移动到#MenuDisplayFocus 或之前,那么这可以在没有:has() 并且它仍然相当有限的浏览器支持的情况下完成。输入字段本身会在视觉上隐藏起来,而 div 会变成它们本来应该出现的样子——正确的 label 元素。如果标签本身也需要当前选择了哪个选项的指标,则可以使用伪元素实现,也基于复选框的:checked状态

标签: html css css-selectors


【解决方案1】:

对于您的情况,您可以这样做,但您需要 :has() 伪类,并且有一个陷阱。

我们可以使用 :has() 来选择父项,因此在本例中我们正在查看 #menu div 并测试第一个输入框。因为第一个输入框实际上是#menu div 的第二个子元素(第一个子元素是 id 为 MenuFocus 的 div),所以我们必须使用 nth-child(2) 来选择第一个输入框。我们不能将 nth-child 选择器与其他规则结合起来以“过滤”不需要的项目(有关详细信息,请参阅this stackoverflow 上的回答),

如果选中此项,那么我们就可以使用后代组合器选择第一张图像。

请注意,目前并非所有浏览器都支持 :has() 。你可以在caniuse.com上查看

可以在css-tricks 找到关于 :has() 的一本很好的入门书,这是 Kevin Powell 写的一本很好的 video

编辑添加nth-of-type 也可以,它使事情更合乎逻辑。下面添加的代码

附言如果您发布实际代码而不是屏幕截图,对于其他贡献者来说会容易得多。它可以帮助您更快地获得答案并避免您的问题被关闭。

#menu:has(input[type="checkbox"]:nth-child(2):checked) #MenuDisplayFocus img:first-child {
  outline: 2px solid red;
}
<div id='menu'>
  <div id='MenuInfo'>
    <div id='MenuDisplayFocus'>
      <img src='https://placekitten.com/200/200'>
      <img src='https://placekitten.com/g/200/200'>
    </div>
    <input type='checkbox' id='SoccerFields' checked='checked'>
    <div id='SoccerfieldsDescription' class='Description'>XXX</div>
    <input type='checkbox' id='Employees'>
    <div id='EmployeesDescription' class='Description'>YYY</div>
  </div>
</div>

第 N 个类型的例子

#menu:has(input[type="checkbox"]:first-of-type:checked) #MenuDisplayFocus img:first-child {
  outline: 2px solid red;
}

#menu:has(input[type="checkbox"]:nth-of-type(2):checked) #MenuDisplayFocus img:nth-child(2) {
  outline: 2px solid blue;
}
<div id='menu'>
  <div id='MenuInfo'>
    <div id='MenuDisplayFocus'>
      <img src='https://placekitten.com/200/200'>
      <img src='https://placekitten.com/g/200/200'>
    </div>
    <input type='checkbox' id='SoccerFields' checked='checked'>
    <div id='SoccerfieldsDescription' class='Description'>XXX</div>
    <input type='checkbox' id='Employees'>
    <div id='EmployeesDescription' class='Description'>YYY</div>
  </div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-31
    • 1970-01-01
    • 2013-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-21
    相关资源
    最近更新 更多