Hover on div affects outside element [duplicate]

吃可爱长大的小学妹 提交于 2021-02-08 07:46:30

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!