March 6, 2013

Shorten string with ellipsis by CSS

Sometimes, when we are designing or developing web site and unfortunately there is a very long sentence appear. It is possible to make the layout distorted and you may think it is not beautiful. At this moment, the idea come from our brain is to replace the sentence by using "...". But, how to do that?

For example, assume we have a sentence below :
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever

Now, we would make use of css text-overflow to illustrate how ellipsis can be appended at the end of the string. Basically you have to set width to make a boundary for the element and overflow hidden.

<style type="text/css">
.w200C 
{
 white-space: nowrap;
 overflow: hidden;
 text-overflow: ellipsis;    
 width: 200px;
}
</style>
The css above is bound the block to 200px, hidden the overflow content and append ellipsis. After applying the css, the sentence will become shorten with ellipsis as below:
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever

Easy? But we may want the whole sentence can be displayed when user mouse over it. We can still use css to solve this problem by reset the overflow, width and white-space to default value.

<style type="text/css">
.w200C:hover
{
 overflow:visible;
 width:auto;
 white-space:normal;
}
</style>
Try to mouse over the sentence below and have a nice day :)
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever

No comments:

Post a Comment