1

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.

In other words, is there a CSS Parent selector?

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>
Z2r
  • 82
  • 1
  • 8
  • 1
    There's no reason to send us to another site. Please see [ask] and create a [live demo](https://stackoverflow.blog/2014/09/16/introducing-runnable-javascript-css-and-html-code-snippets/) using the post editor. – isherwood Sep 20 '22 at 16:40

2 Answers2

0

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>
async await
  • 1,967
  • 1
  • 8
  • 19
-1

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>
isherwood
  • 58,414
  • 16
  • 114
  • 157