CSS width transition not working at all

steo picture steo · Sep 25, 2013 · Viewed 42.5k times · Source

Hi I'm trying to animate the width of the span inside the a of this nav

<nav class="navigator">
   <ul>
    <li><a href="#home">H<span>home</span></a></li>
    <li><a title="What?" href="#what">W<span>what</span></a></li>
    <li><a title="Porfolio" href="#works">P<span>works</span></a></li>
    <li><a title="Who?" href="#who">W<span>who</span></a></li>
    <li><a title="Where?" href="#where">W<span>where</span></a></li>
  </ul>
</nav>

here it is the CSS

header nav ul li a{
    position: relative;
    width: 40px;
    display: block;
    text-decoration: none;
    font-size: 18px;
    color: #000;
}
header nav ul li a:hover span{
    width: auto;
    overflow: visible;
    text-align: right;
}
header nav ul li a span{
    position: absolute;
    width: 0;
    right: 45px;
    overflow: hidden;
    transition:width 0.25s;
    -webkit-transition:width .25s;
    -moz-transition: width 0.25s;
    font-size: 16px;
}

As you can see I'm trying to animate the width, but, instead of growing gradually the span is only showing up without any transition. To let you figure out the effect that I'm trying to get check out the nav of this site :http://kitkat.com/

I made a fiddle of my own nav:http://jsfiddle.net/ZUhsn/ where the problem comes out.

Hope I gave you all the information to try to solve my issue. Cheers.

Answer

Mister Epic picture Mister Epic · Sep 25, 2013

Try this:

header nav ul li a:hover{}
header nav ul li a:hover span{
    width: 100%; /* YOU'LL NEED TO ADJUST THIS, IT CANNOT BE AUTO*/
    overflow: visible;
    text-align: right;
}

header nav ul li a span{
    position: absolute;
    width: 0;
    right: 45px;
    overflow: hidden;
    transition:width 0.25s;
    -webkit-transition:width .25s;
    -moz-transition: width 0.25s;
    font-size: 16px;
    display:block; /*HERE IS MY OTHER CHANGE*/
}

http://jsfiddle.net/ZUhsn/4/

Two issues:

Firstly, span is an inline element by default, so it doesn't have a width like you would expect. By applying display:block;, we turn it into a block-level element with width.

Secondly, you were transitioning to a width value of 'auto'. Transitions can only animate across numerical values, so you'll have to give your ending transition a measurement with units.