membersound
membersound

Reputation: 86747

How to enable a css tag only during hover?

I'm creating a badge notification using css, but I want to show it only during hovering of the outer element. It that possible?

<img src..><span class="badge">5</span></img>

The badge is created as follows from css:

/*@see http://cssdeck.com/labs/menu-with-notification-badges*/
img .badge {
  display: block;
  position: absolute;
  top: -12px;
  right: 3px;
  line-height: 16px;
  height: 16px;
  padding: 0 5px;
  font-family: Arial, sans-serif;
  color: white;
  text-shadow: 0 1px rgba(0, 0, 0, 0.25);
  border: 1px solid;
  border-radius: 10px;
  -webkit-box-shadow: inset 0 1px rgba(255, 255, 255, 0.3), 0 1px 1px rgba(0, 0, 0, 0.08);
  box-shadow: inset 0 1px rgba(255, 255, 255, 0.3), 0 1px 1px rgba(0, 0, 0, 0.08);

  background: #67c1ef;
  border-color: #30aae9;
  background-image: -webkit-linear-gradient(top, #acddf6, #67c1ef);
  background-image: -moz-linear-gradient(top, #acddf6, #67c1ef);
  background-image: -o-linear-gradient(top, #acddf6, #67c1ef);
  background-image: linear-gradient(to bottom, #acddf6, #67c1ef);
}

Question: how can I show the badge only when hovering the specific img where the badge class is applied at?

Upvotes: 2

Views: 513

Answers (2)

zif
zif

Reputation: 51

jQuery .hover() function can also do this, remember $(".badge").hide() when load the page.

Upvotes: 0

James Donnelly
James Donnelly

Reputation: 128791

For starters the img element is a standalone self-closing element and doesn't doesn't allow children elements. With that markup most browsers will convert your code to:

<img src... />
<span class="badge">5</span>

Some may also treat that </img> tag as a second img element.

Separating the img element from the span as shown above is what we firstly want to do anyway, so adjust your HTML to reflect that. Then we can implement the adjacent sibling combinator (+) so select our span element when the img element is being overed over:

img:hover + .badge {
    ...
}

Remember to hide the .badge element by default.

.badge {
  display: none;
}

img:hover + .badge {
  display: block;
}
<img src="http://placehold.it/320x140&text=Hover%20Here" />
<span class="badge">Hello, world!</span>

Upvotes: 3

Related Questions