user3310334
user3310334

Reputation:

Show image next to element on hover?

When I hover a .tags I'd like to show the image https://mal-stats.glitch.me/tagslegend.png next to it.

Test it out on this page.

I'd like to see this when not hovering .tags (all the cells in that final column have tags class):

enter image description here

and this while hovering the first .tags cell:

enter image description here

The image should align with the cell that is being hovered.


I know how I would do this with javascript. I also know how I could do this if I could change the html.

Because it's a user-stylesheet though I can only use CSS.


How do I do this in pure CSS?

I'm assuming I'd have to use pseudo-elements somehow, but I don't have enough experience to even know where to begin.

This is basically where I'm at:

.tags:hover:after {
  background-image: url(https://mal-stats.glitch.me/tagslegend.png);
}

but it doesn't work. I've seen examples that set display: block and then width and height, but the image from /tagslegend.png is dynamic. If that's a huge problem I can change that, but a solution that works with any widths and heights is best.


The code will need to run on this page, but b/c it's been requested in comments here's a minimal example:

.tags:hover:after {
  background-image: url(https://mal-stats.glitch.me/tagslegend.png);
}
<table>
  <tr>
    <td>Foo</td>
    <td>Bar</td>
    <td>Baz</td>
    <td class="tags">Hover me</td>
  </tr>
</table>

Upvotes: 0

Views: 484

Answers (3)

showdev
showdev

Reputation: 29168

Since you're using a pseudo-element with a background image, you'll need to include content, give it some width/height, and set a display mode that allows setting width and height.

Here's an example:

.tags:hover:after {
  content: "";
  display: inline-block;
  width: 10px;
  height: 10px;
  background-image: url(//via.placeholder.com/10x10);
}
<table>
  <tr>
    <td>Foo</td>
    <td>Bar</td>
    <td>Baz</td>
    <td class="tags">Hover me</td>
  </tr>
</table>

For reference, see:
Why do the :before and :after pseudo-elements require a 'content' property?

Upvotes: 1

Michał Perłakowski
Michał Perłakowski

Reputation: 92471

Try this:

.tags { 
  position: relative;
}

.tags:hover::after {
  content: '';
  position: absolute;
  left: calc(100% + 30px);
  top: 0;
  width: 1000px;
  height: 1000px;
  background-image: url(https://mal-stats.glitch.me/tagslegend.png);
  background-repeat: no-repeat;
}

Upvotes: 0

Westwick
Westwick

Reputation: 2487

You almost have it, you should be able to do it like this:

.tags { 
    position: relative;
}

.tags:hover:after {
    position: absolute;
    right: -200px;
    top: 0;
    width: 200px;
    height: 30px;
    background-image: url(https://mal-stats.glitch.me/tagslegend.png);
}

You'll have to play with the width/height position-right to get it exactly how you want it.

Upvotes: 1

Related Questions