...
[div class="container"]
[div class="text"]
[[Text]]
[/div]
[div class="ellipsis"]...[/div]
[/div]
[style]
body {
margin: 20px;
}
.container{
position: relative;
background-color: #bbb;
padding: 20px;
}
.text {
overflow: hidden;
/*text-overflow: ellipsis; Not needed */
line-height: 16px;
max-height: 48px; /* Multiples of line-height */
}
.ellipsis {
position: absolute;
bottom: 20px;
right: 20px;
height: 16px;
width: 30px;
background-color: inherit;
padding-left: 8px;
}
[/style]
The pure css solution works when the text overflows the available space. However, short text strings do not overflow the space and should not be given an ellipsis.
To solve the short text problem, Implement the javascript solution, below, as well:
[script]
function getTextWidth(text, font) {
var canvas = getTextWidth.canvas ||
(getTextWidth.canvas = document.createElement("canvas"));
var context = canvas.getContext("2d");
context.font = font;
var metrics = context.measureText(text);
return metrics.width;
};
$(".container").each(function() {
if (getTextWidth(
$(this).find(".text").text(),
$(this).find(".text").css("font")
) < ($(this).find(".text").width() * 3)) { // Multiplier is number of lines to show
$(this).find(".ellipsis").remove();
}
});
[/script]