0

When I hover the over an image img1, I want the corresponding text text1 to appear. The same goes for img2 and text2, and so on.

Here is the code of what I tried, but the text doesn't appear when I hover on the images. What am I doing wrong?

here is my html

<section>
    <div class="planche">
        <img class="img1" src="./images/1.jpg">
        <img class="img2" src="./images/2.jpg">
        <img class="img3" src="./images/3.jpg">
    </div>
    <div class="text1">
        <p>
            TEXTE 1
        </p>
    </div>
    <div class="text2">
        <p>
            TEXTE 2
        </p>
    </div>
    <div class="text3">
        <p>
            TEXTE 3
        </p>
    </div>      
</section>

and here is my css:

.img1:hover .text1 {
  opacity: 1;
  background-color: white;
}
Ibu
  • 42,752
  • 13
  • 76
  • 103
  • 1
    Is it possible for you to use JavaScript / jQuery for this? I don't believe it is possible in plain CSS with the current structure - Alternative, could the text divs be moved into the planche div – Shiny Jan 05 '20 at 01:35
  • This is because of how css works. Your notation means: “ if `.img1` is being hovered, apply rules to `.text1` that is within the `.img1`. This cannot work. The best you can do with css use siblings selector but it would require changes to html too. – Akxe Jan 05 '20 at 01:36
  • While jQuery is not required, JavaScript is as there is no parent selector in CSS, so there’s no way to select the relevant `
    ` based on the hovered image.
    – David Thomas Jan 05 '20 at 01:37
  • jQuery is NOT needed for this – Rob Jan 05 '20 at 01:37
  • Yes, I've already edited my comment to show this – Shiny Jan 05 '20 at 01:38

1 Answers1

1

One pure CSS approach is to surround each image in a semantically friendly figure and use the general sibling combinator (~) to target each associated text div.

From MDN:

The general sibling combinator (~) separates two selectors and matches the second element only if it follows the first element (though not necessarily

immediately), and both are children of the same parent element.

.planche1:hover ~ .text1,
.planche2:hover ~ .text2,
.planche3:hover ~ .text3 {
  color: red;
}
<section>
  <figure class="planche planche1">
    <img class="img1" src="http://placekitten.com/100/50?image=1" alt="description goes here">
  </figure>
  <figure class="planche planche2">
    <img class="img2" src="http://placekitten.com/100/50?image=2" alt="description goes here">
  </figure>
  <figure class="planch planche3">
    <img class="img3" src="http://placekitten.com/100/50?image=3" alt="description goes here">
  </figure>
  <div class="text1">
    <p>
      TEXTE 1
    </p>
  </div>
  <div class="text2">
    <p>
      TEXTE 2
    </p>
  </div>
  <div class="text3">
    <p>
      TEXTE 3
    </p>
  </div>
</section>

jsFiddle

Andy Hoffman
  • 18,436
  • 4
  • 42
  • 61