Danyx Danyx - 5 months ago 19
CSS Question

Show hidden text on hover with animation

I have the following structure:

HTML:

<ul>
<li>
<span>asd</span> adsafsadlvjnsd
</li>
</ul>


CSS:

span {
width: 0;
}
li:hover span {
width: 60px;
}


This means that the content in the span is initially hidden but shown when the item is hovered, currently if the content on the li is too big it simply pushes the content down, is there a way to only push as much content as necessary? I tried using word-break but that didn't seem to work.

Also, I want to have the slide animation when hovering.




Answer

You can use width: auto; instead of fixed width on hover.

span {
  width: 0;
  display: inline-block;
  vertical-align: top;
  overflow: hidden;
}

li:hover span {
  width: auto;
}
<ul>
  <li>
    <span>hello</span> world
  </li>
</ul>

For continuous text you can apply white-space: nowrap;. For animation you probably need to use some Javascript if the span can't be fixed width, since the current CSS doesn't allow to use auto width / height for transition. Below I use jQuery to get the width of the span.

jsFiddle

spanWidth = $('li span').width();
$('li span').css('width', '0');

$('li').hover(
  function() {
    $('span', this).css('width', spanWidth);
  },
  function() {
    $('span', this).css('width', '0');
  }
);
/*hide the span, works together with the script*/
span {
  display: inline-block;
  white-space: nowrap;
  vertical-align: top;
  overflow: hidden;
  transition: all .5s;
}
/*get rid of the extra whitespace, use it as needed*/
span { margin-right: -4px; }
li:hover span { margin-right: 0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul>
  <li>
    <span>Lorem ipsum</span> dolor sit amet, consectetur adipiscing elit. Praesent eu tincidunt velit. Nam gravida venenatis mollis. Cras sed lacus varius, pretium nulla eget, auctor diam. Suspendisse ullamcorper ex nisi, non scelerisque lorem pellentesque id. Mauris non bibendum libero, vel efficitur lorem.
  </li>
</ul>

Comments