简体   繁体   English

父亲兄弟元素子的CSS选择器

[英]CSS Selector for Child of Parent's Sibling Element

If I've got this: 如果我有这个:

<div class="parent">
    <a href="#" id="trigger">Trigger</a>
</div>
<div class="sibling">
    <div id="change">Hello</div>
</div>

Is there a selector to grab #change when #trigger is hovered upon? 当#trigger徘徊时,是否有一个选择器来抓取#change?

Like upon hover of #trigger, change the background of .sibling's #change element. 就像在#trigger上悬停一样,更改.sibling的#change元素的背景。

I'm looking for a pure CSS solution without javascript. 我正在寻找一个没有javascript的纯CSS解决方案。

In a word: no. 总之一句:不。

Given the current structure of your HTML (and the current state of CSS selectors), this is not possible. 鉴于HTML的当前结构(以及CSS选择器的当前状态),这是不可能的。 Perhaps we will get something like this in CSS4, but traversal like this is best left up to Javascript. 也许我们会在CSS4中得到类似的东西,但这样的遍历最好留给Javascript。

You can obviously restructure your markup, and use the sibling selector: 您显然可以重构您的标记,并使用兄弟选择器:

HTML HTML

<div class="parent">
    <a href="#" id="trigger">Trigger</a>
    <div class="sibling">
       <div id="change">Hello</div>
    </div>
</div>

CSS CSS

#trigger:hover + .sibling #change {
  color:red; 
}

codepen codepen

No. You cannot achieve this using CSS only. 不,你不能仅使用CSS来实现这一点。 Javascript is a good option in this case.. 在这种情况下,Javascript是一个不错的选择..

You can however detect the .parent being hovered (which will solve your problem if the parent surrounds exactly the trigger): 但是,您可以检测到.parent正在悬停(如果父项完全包围触发器,则会解决您的问题):

.parent:hover + .sibling div#change{background:red;}

(markup stays the same jsFiddle ) (标记保持相同的jsFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM