This post is for a CSS solution, but the post is quite old, so just in case others stumble on this and are using a modern JS framework such as Angular 4+, there is a simple way to do this through Angular Pipes without having to mess around with CSS.
There are probably "React" or "Vue" ways of doing this as well. This is just to showcase how it could be done within a framework.
truncate-text.pipe.ts
/**
* Helper to truncate text using JS in view only.
*
* This is pretty difficult to do reliably with CSS, especially when there are
* multiple lines.
*
* Example: {{ value | truncateText:maxLength }} or {{ value | truncateText:45 }}
*
* If maxLength is not provided, the value will be returned without any truncating. If the
* text is shorter than the maxLength, the text will be returned untouched. If the text is greater
* than the maxLength, the text will be returned with 3 characters less than the max length plus
* some ellipsis at the end to indicate truncation.
*
* For example: some really long text I won't bother writing it all ha...
*/
@Pipe({ name: 'truncateText' })
export class TruncateTextPipe implements PipeTransform {
transform(value: string, ...args: any[]): any {
const maxLength = args[0]
const maxLengthNotProvided = !maxLength
const isShorterThanMaximumLength = value.length < maxLength
if (maxLengthNotProvided || isShorterThanMaximumLength) {
return value
}
const shortenedString = value.substr(0, maxLength - 3)
return `${shortenedString}...`
}
}
app.component.html
<h1>{{ application.name | truncateText:45 }}</h1>
textarea
orinput
there is a max length (maxlength="50"
this is in the HTML) property for them or you would have to use Javascript. Also I think I misread this, setting a width will force the sentence to drop to the next line when it hits the end. This is default behaviour. – Greathearted