How to display a set of text (<p>) when mouse hovers over a certain image?

Ok, so let me describe the goal first. I am making a birthday page for my best friend. I asked some of her other close friends to give a message, birthday greeting, etc., for her which I will post/display on the website. My plan was to insert a picture of let’s say “friend A”. And then when viewing the webpage, when the viewer hovers over “friend A”'s picture, a corresponding “text box” (idk the correct term) appears over the picture of “friend A” containing that person’s message for the celebrant. I want to implement this if possible, all in HTML5 and CSS3. I have totally no idea how to write the code for this task. Any help would be appreciated.

P.S. If that task is possible, would the code also work if let’s say, she views the page on a touchscreen device? Would the “text box” still appear if she touches the image of “friend A”?

Thanks

Hi @jcrmontemayor20, the basic approach would be a simple :hover effect, like

HTML

<div class="container">
  <img src="http://lorempixel.com/400/200/" alt="foo">
  <p>Some text</p>
</div>

CSS

.container {
  position: relative;
}

.container p {
  display: none;
  position: absolute;
  top: 0;
}

.container:hover p {
  display: block;
}

However, this may or may not apply when touching the element. For this there are some possible solutions, e.g. you could turn those .container elements to <a> tags and use the CSS :target pseudo-class on them, or you could make them labels and use the “checkbox hack”:

HTML

<input type="checkbox" id="check1" class="touch-check">
<label class="container" for="check1">
  <img src="http://lorempixel.com/400/200/" alt="bar">
  <p>Some text</p>
</label>

CSS

.container {
  position: relative;
  display: block;
}

.container p {
  display: none;
  position: absolute;
  top: 0;
}

.touch-check {
    display: none;
}

.touch-check:checked + .container p {
    display: block;
}

This way you can “check” and “uncheck” those image texts individually; with the :target solution there would only one image text being visible at a time, and couldn’t as easily be hidden again.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.