To achieve this effect, a combination of a little JavaScript and the CSS property text-overflow
can be used.
By applying white-space: nowrap
, the text will remain on a single line without wrapping onto multiple lines.
Setting the width to a fixed 200px and using overflow: hidden
will truncate the text that exceeds the specified width.
Adding text-overflow: ellipsis
will display three dots at the end of the truncated text.
The "Show more"/"Show less" buttons simply toggle between displaying the full text and the truncated version.
var $text = jQuery(".text");
var $button = jQuery(".show-more");
$button.on("click", function(){
$text.toggleClass("is-expanded");
if($text.hasClass("is-expanded")){
$button.text("Show less");
} else {
$button.text("Show more");
}
});
.text {
width: 200px;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}
.text.is-expanded {
white-space: initial;
overflow: visible;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text">
This is very very long text and it is hidden at the end.
This is very very long text and it is hidden at the end. This is very very long text and it is hidden at the end.
This is very very long text and it is hidden at the end.
</div>
<button class="show-more">Show more</button>