11

I have following HTML:

<ul>
    <li>
        <a href="#">
            <h2>title</h2>
        </a>
    </li>
     <li>
        <a href="#">
            <h2>title</h2>
        </a>
    </li>
     <li>
        <a href="#">
            <h2>title</h2>
        </a>
    </li>
</ul>

CSS

ul {
    list-style: none;  
    text-align: center;
}
ul li {
    position: relative;
    float: right;
    margin-right: 20px;
    width: 30%;
}
ul li {
    transition: all 0.3s;
}
ul li:hover {
    top: -10px;
}
ul li> a{
    color: red;
}

The question is the transition does not work with moz, it works on webkit. How do I implement this in a cross browser way?

DEMO

4

4 回答 4

17

Browsers don't apply transition on a property if an initial value for it is not specified in the element. Hence, adding top: 0px to ul li will solve the issue.

ul {
  list-style: none;
  text-align: center;
}
ul li {
  position: relative;
  float: right;
  margin-right: 20px;
  top: 0px; /* this line was added */
  width: 30%;
}
ul li {
  transition: all 0.3s;
}
ul li:hover {
  top: -10px;
}
ul li> a {
  color: red;
}
<!-- Library included just to avoid prefixes so that users with older browser can view -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>

<ul>
  <li>
    <a href="#">
      <h2>title</h2>
    </a>
  </li>
  <li>
    <a href="#">
      <h2>title</h2>
    </a>
  </li>
  <li>
    <a href="#">
      <h2>title</h2>
    </a>
  </li>
</ul>

Note: I would also suggest using the same option (transform) as mentioned in Mr_Green's answer.

于 2013-08-26T09:45:33.863 回答
4

I don't know why top css property is acting weird to do animation in firefox even it is listed as animation behaviour property in css.

Anyway, using margin-top instead of top is working fine in Firefox.

But I would like to suggest going with transform's "translateX" and "translateY" css properties instead of using positioning from next time because it is efficient. (recommended by Paul Irish)

于 2013-08-26T09:32:36.663 回答
3

Try this:

ul li { 
    /* standard property and other vendor prefixes */
    -moz-transition: -moz-transform 0.3s;
}
ul li:hover {
    /* standard property and other vendor prefixes */
    -moz-transform: translateY(-10px);
}
于 2013-08-26T09:04:52.407 回答
2

It's definitely not the transition declaration or anything else in the CSS you've written --- try adding opacity:.5 to the hover state and you'll see it animate fine.

So, for some reason, Firefox is not transitioning the top property. To be honest, I don't know why yet. My solution for now would be to use a CSS transform to move the item up 10px instead:

ul li:hover {
    -o-transform: translateY(-10px);
    -ms-transform: translateY(-10px);
    -moz-transform: translateY(-10px);
    -webkit-transform: translateY(-10px);
    transform: translateY(-10px);

}

This successfully animates in Firefox as you can see here:

http://jsfiddle.net/y7yQQ/7/

于 2013-08-26T09:26:48.857 回答