Is there a css selector which selects an element o

2019-02-20 14:29发布

问题:

This question already has an answer here:

  • Is there a CSS parent selector? 26 answers
  • How to change one element while hovering over another 4 answers

Code explains better than words

<div class="parent">
  <span class="child"></span>
</div>
<div class="outside"></div>

What I want to do

.child:hover ? .outside { }

where ? is the selector I'm looking for

回答1:

Selectors express structural relationships between elements. When you ask for a selector for an element that is "outside" another element, you're looking for a combinator that says "this element appears outside the containing scope of this other element".

There is no such combinator.

You could conceivably select specifically the .outside sibling of .parent, but then you run into another problem that there is no parent selector for matching .parent relative to .child:hover like there is for matching .child:hover relative to .parent (that is, .parent > .child:hover).

See also: How do I select an element based on the state of another element in the page with CSS?



回答2:

The easiest way would to be to make the .parent class the element needed to hover over.

Then you could do

.parent:hover ~ .outside {

}


回答3:

With the following html structure:

<div class="parent">
<span class="child"></span>
</div>

<div class="outside"></div>

since there is no reliable parent selector in CSS, you can select .outside only in 5 ways:

  1. Directly.
  2. If it is a sibling of .parent.
  3. If it is a child of .parent.
  4. If it is a sibling of .child.
  5. If it is a child of .child.

Since .outside is neither a sibling nor a child of .child, nor is it a child of .parent, your only remaining relationship via which to select .outside is as a sibling of .parent.

This isn't really what you want, if you only want the presentation of .outside to change only when you hover over .child.

I'm no fan of using javascript to influence presentation when CSS can already handle the task, but in this case, CSS cannot handle the task and the javascript is elementary:

var child = document.getElementsByClassName('child')[0];
var outside = document.getElementsByClassName('outside')[0];

function childHover() {
outside.classList.toggle('childhover');
}

function initialiseChildHover() {
child.addEventListener('mouseover',childHover,false);
child.addEventListener('mouseout',childHover,false);
}

window.addEventListener('load',initialiseChildHover,false);
.parent {
display: inline-block;
width: 200px;
height: 200px;
background-color: rgba(255, 0, 0, 1);
}

.child {
display: inline-block;	
width: 100px;
height: 100px;
margin: 50px;
background-color: rgba(255, 255, 0, 1);
}

.outside {
display: inline-block;
width: 150px;
height: 150px;
background-color: rgba(0, 255, 0, 1);
}

.outside.childhover {
background-color: rgba(0, 0, 255, 1);
}
<div class="parent">
<span class="child"></span>
</div>
    
<div class="outside"></div>