Search code examples
htmlcsshoverselectorparent

How to use pure CSS to control other elements under same parent?


here is the simple example from codepen Codepen

I'm trying to make a few area which belong to the same parent element,
and when I hover one of them, the others' opacity will decrease, or something else style changing.

For example, when I hover the second element, the first element which has the same parent would change its background-color.

I use the word area at the first paragraph means the child doesn't really have to be a div, it could be a li or a p or other elements.
to solve this problem, it could be any type of element.

html looks like this:

<!-- html -->
<div class="parent">
  <div class="one"></div>
  <div class="two"></div>
  <div class="three"></div>
  <div class="four"></div>
</div>

I tried E ~ F rule to solve this problem, and I've already known it will only work at the first div which is the first child of parent.

except javascript, is there any other way to make this feature with pure css?
thx


Solution

  • When you hover the .parent, change the style of all children that are not hovered as well (pen):

    .parent {
      width: 100px; /** limit the width of the parent, so you can't hover it, without hovering one of the children as well **/
      margin:10px;
    
      &:hover > div:not(:hover) { /** only change the background of divs you don't hover as well **/
        background: red;
      }
    
      div{
        width:100px;
        height:100px;
        border:1px solid black;
      }
    }