HTML & CSS: How to expand text on hover

In this article, I will show how to display short text on a web page that can expand to longer text on hover. The trick is to use two spans inside of a div. The first span contains the shorter text and the second span contains the longer text. For example:

<div class="expanded-text">
  <p class="text">
    <span class="short-name">On The Origin Of Species</span>
    <span class="longer-name">On The Origin Of Species By Means Of 
      Natural Selection, Or The Preservation Of Favoured Races In 
      The Struggle For Life</span>
  </p>
</div>

Then in the CSS, the longer name starts out hidden with display:none;

span.longer-name{
 display:none;
}

The magic happens when hovering over the div. On hover, the short name is hidden and the longer name is displayed in the CSS. For example:

/* On hover, hide the short name */
.expanded-text:hover span.short-name{
 display:none;
}
/* On hover, display the longer name.  */
.expanded-text:hover span.longer-name{
 display:block;
}

Here is the complete CSS:

body {
    background-color: #555;
}
/* Container for the text that expands on hover */
.expanded-text {
    width: 100%;
}
/* Longer name hidden by default  */
span.longer-name{
    display:none;
}
/* On hover, hide the short name */
.expanded-text:hover span.short-name{
    display:none;
}
/* On hover, display the longer name.  */
.expanded-text:hover span.longer-name{
    display:block;
}
/* Decorate the text */
.text {
   color: white;
   font-size: 24px;
}

Here is a demo on Codepen:

See the Pen Expand text on hover by Chris Nielsen (@Chris_Nielsen) on CodePen.0