CSS make a hover affect other items

Viewed 20

I want everything inside the #parent div to change width when I hover on an image, but the image my cursor is on not to change.

this is my code right now that doesn't work:

img {
  width: 340px
}

body {
  background-color: black;
}

img:hover~#parent {
  width: 34px
}
<body>
  <div id="parent">
    <img src="https://www.tazzadesign.com/wp-content/uploads/sites/65/2013/11/dummy-image-square.jpg">
    <img src="https://www.tazzadesign.com/wp-content/uploads/sites/65/2013/11/dummy-image-square.jpg">
    <img src="https://www.tazzadesign.com/wp-content/uploads/sites/65/2013/11/dummy-image-square.jpg">
  </div>
</body>

2 Answers

You're trying to select a parent element, which won't work. CSS doesn't do that. Then, the tilde operator (~) is a subsequent sibling combination selector (docs). It'll only affect siblings after the active one.

See the linked duplicates for possible solutions.

img {
  width: 340px
}

body {
  background-color: black;
}

img:hover~img {
  width: 34px
}
<body>
  <div id="parent">
    <img src="https://www.tazzadesign.com/wp-content/uploads/sites/65/2013/11/dummy-image-square.jpg">
    <img src="https://www.tazzadesign.com/wp-content/uploads/sites/65/2013/11/dummy-image-square.jpg">
    <img src="https://www.tazzadesign.com/wp-content/uploads/sites/65/2013/11/dummy-image-square.jpg">
  </div>
</body>

The linked possible duplicates probably have a good answer for you, but this problem can be solved with js as well using the mouseover / mouseout events.

const parent = document.querySelector(".parent");
const children = [...document.querySelectorAll(".child")];
children.forEach(child => {
  child.addEventListener(
    "mouseover", 
    () => parent.classList.add("child-hover")
  );
  child.addEventListener(
    "mouseout", 
    () => parent.classList.remove("child-hover")
  );
});
.parent {
  position: absolute;
  inset: 0;
  display: flex;
  align-items: center;
  justify-content: space-around;

  --b-color: blue;
  border: 5px solid var(--b-color);
  
  transition: 0.1s;
}

.parent.child-hover {
  --b-color: green;
}

.child {
  --size: 10rem;
  height: var(--size);
  width: var(--size);
  --b-color: gray;
  border: 5px solid var(--b-color);
  
  transition: 0.1s;
}

.parent.child-hover .child {
  transform: scale(0.1);
}

.parent.child-hover .child:hover {
  transform: scale(1);
}

.child:hover {
  --b-color: lightgreen;
}
<div class="parent">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
</div>

Related