问题
I'm trying to affect an outside element when a div is hovered. Something like this:
<div class="affected">
Hi
</div>
<div>
<div class="hover-me"></div>
</div>
CSS:
.hover-me:hover ~ .affected {
color:
}
I've tried with other sibling selectors but it doesn't work.
回答1:
With pure CSS that's gonna be as tricky as it gets.
An approach, IF you don't need pointer-events (hover, clicks, etc) on the div that contains the hoverable child, is setting the container as actionable div, disabling pointer-events, resetting them on the child, and using some sort of magic to have the siblings in reverse order on your HTML so they can be targeted with sibling selectors (as you cannot target previous siblings)
Something like
body{
/*switches the oder of .affected and .hover-container, so .affected can be bellow in the HTML and be targeted with sibling selectors, while showing above*/
display:flex;
flex-direction:column-reverse;
}
.hover-container:hover ~ .affected{
/*targets the action on the container*/
background:red;
}
.hover-container{
/*disables pointer-events on the container, so entering it won't cause the hover effect on the sibling*/
pointer-events:none;
}
.hover-me{
/*resets pointer-events on the .hover-me child, so the previous :hover we set for the container will work only when hovering this child*/
pointer-events:auto;
cursor:pointer;
}
div{
border:2px solid grey;
margin:20px 40px;
text-align:center;
}
<div class="hover-container">
this is the hover container
<div class="hover-me">hover me</div>
</div>
<div class="affected">
affected
</div>
But that's probably a not so common scenario, at that point you'll be better off with a JS approach.
来源:https://stackoverflow.com/questions/49022545/hover-on-div-affects-outside-element