Question

I am experimenting with using CSS to display genereated content in pseudo-elements.

The hover state does not work correctly. The content generated from the last button appears before the mouse actually hovers over the button if the mouse enters from the bottom. Is there a way to fix this so that the content only appears when the button is hovered over?

Here is a fiddle for the example: http://jsfiddle.net/Ts6qy/

Here is my HTML:

<div class="container">
  <span data-title="Number 1">Item 1</span>
  <span data-title="Number 2">Item 2</span>
  <span data-title="Number 3">Item 3</span>
  <span data-title="Number 4">Item 4</span>    
</div>

Here is my CSS:

.container {
  position: relative;
  text-align: center;
  padding: 20px 0;

  max-width: 420px;
  margin: 0 auto;
}

.container span {
  display: inline-block;
  padding: 2px 6px;
  background-color:#78CCD2;
  color:#FFFFFF;
  border-radius:4px;
  margin:3px;
  cursor:default;
}   

/* Pseudo-elements can even access attributes in their parent elements */
.container span::before {
  position:absolute;
  bottom: 0;
  left: 0;
  width: 100%;

  content: attr(data-title); 

  color: #666666;
  font-weight:bold;
  text-align: left;
  opacity: 0;
  /*Animate the transistions */
  -webkit-transition: opacity 0.4s;
  transition: opacity 0.4s;
}

.container span:hover::before {
  opacity: 1;
}
Was it helpful?

Solution 2

Take a look http://jsfiddle.net/Ts6qy/26/

This width: 100%; has been removed from .container span::before.

So, this way, the before just shows up when hovered it self or when on of those spans is hovered.

I don't know if you really do need what width: 100%; anyway, this method works and you can keep transitions.

OTHER TIPS

Another approach, to make clearer what is happening:

Add pointer-events: none to the pseudo element:

.container span::before {
    position:absolute;
    bottom: 0;
    left: 0;
    width: 100%;

    content: attr(data-title); 

    color: #666666;
    font-weight:bold;
    text-align: left;
    opacity: 0;
    /*Animate the transistions */
    -webkit-transition: opacity 0.4s;
    transition: opacity 0.4s;
    pointer-events: none;
}

And it solves the problem (of course in supporting browsers).

What was happening is that the hover was triggered by the span and also by the pseudo element of the span.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top