0

I'm trying to change a display property when hover another div.

.pc-hover {
  display: none;
}
.pc-content-image img:hover + .pc-hover {
  display: block;
}
<div class="profile-content">
  <div class="pc-hover">{hover}</div>
  <div class="pc-header">{head}</div>
  <div class="pc-content">
    <div class="pc-content-image">
      <img src="https://via.placeholder.com/300" alt="placeholder" />
    </div>
    <div class="pc-content-text">
      <p>{text}</p>
      <p>{text2}</p>
    </div>
  </div>
</div>

Initially, pc-hover is not showing until the mouse hovers the image from pc-content-image. But nothing happens when I hover over the image.

I've seen some references from Using only CSS, show div on hover over another element, but I don't understand how to do it.

Tried to use + and ~, but not working.

Is there a way to achieve this? Appreciate any kinda helps, thanks.

anatolhiman
  • 1,762
  • 2
  • 14
  • 23
itsMe
  • 133
  • 12

1 Answers1

2

Two problems:

  1. Adjacent sibling operator (+) will only work if the sibling element comes after the hovered element in the html source. So I moved it down below the image div in my example.

  2. You attach the hover event to the img element, which is inside of a div. That image doesn't have any adjacent siblings, so your CSS won't work. For this to work we have to listen for hover on the parent div.pc-content which is the adjacent sibling of div.pc-hover.

I'm not sure if there's a "preceding sibling operator" in CSS, otherwise you'll have to use flex and flex-direction: column-reverse (for example) in order to get your hidden div in the right position below the image in the source, but above it in the output.

.pc-hover {
  display: none;
}

.pc-content-image img:hover {       
  cursor: pointer;
  border: 1px solid red;
}

.pc-content-image:hover + .pc-hover {
  display: block;
  height: 10rem;
  background: red;
  margin-bottom: 1rem;
}
<div class="profile-content">
  <div class="pc-header">{head}</div>
  <div class="pc-content">
    <div class="pc-content-image">
      <img src="https://via.placeholder.com/100" alt="placeholder" />
    </div>
   <div class="pc-hover">{hover}</div>
    <div class="pc-content-text">
      <p>{text}</p>
      <p>{text2}</p>
    </div>
  </div>
</div>
anatolhiman
  • 1,762
  • 2
  • 14
  • 23