Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show dots on the nth line of a text if it breaks with CSS

I want to show dots on the nth (in my case 2nd) line of a text if it breaks. I saw this and this answers but I didn't manage to get the thing working in my case.

Here's a fiddle.

.overme {
    width: 300px;
    height: 60px;
    line-height: 30px;
    overflow:hidden; 
    font-size: 30px;
    color: red;
    background: #333;
    /*The problematic part is below*/
    white-space:nowrap; 
    text-overflow: ellipsis;
}
like image 353
Yulian Avatar asked Feb 01 '16 09:02

Yulian


1 Answers

Solution 1:

Use the webkit only -webkit-line-clamp property for 2 lines.

.overme {
    width: 300px;
    height: 60px;
    line-height: 30px;
    overflow:hidden; 
    font-size: 30px;
    color: red;
    background: #333;

    /*The problematic part is below*/
    white-space:nowrap; 
    text-overflow: ellipsis;
}
    
.overme {
    white-space: normal;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}
<div class="overme">
    how much wood can a woodchuck chuck if a woodchuck could chuck wood?
</div>

Solution 2

Use an :after pseudo element, aligned to the bottom right corner. This only works if your text is static and you known beforehand that will overflow the container.

.overme {
    width: 300px;
    height: 60px;
    line-height: 30px;
    overflow:hidden; 
    font-size: 30px;
    color: red;
    background: #333;
    position: relative;
}
    
.overme:after {
    display: inline-block;
    position: absolute;
    right: 0;
    bottom: 0;
    content: '...';
}
<div class="overme">
    how much wood can a woodchuck chuck if a woodchuck could chuck wood?
</div>

Solution 3 - Cross-browser

This JS solution compares the height of the parent container (div) against the content text. If the text height is greater than the parent's height, then a .overflows class is added to the parent.

To test this, delete some text so that it fits all in the parent. You will no longer see the dots.

$(".overme").each(function () {
  var $elem = $(this);
  $elem.addClass($elem[0].scrollHeight > $elem.height() ? 'overflows' : null);
});
.overme {
    width: 300px;
    height: 60px;
    line-height: 30px;
    overflow:hidden; 
    font-size: 30px;
    color: red;
    background: #333;
    position: relative;
}
    
.overme.overflows:after {
    display: inline-block;
    background: #333;
    position: absolute;
    right: 2px;
    bottom: 0;
    content: '...';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="overme">
    how much wood can a woodchuck chuck if a woodchuck could chuck wood?
</div>
like image 131
Jose Rui Santos Avatar answered Sep 28 '22 02:09

Jose Rui Santos