Without further ado, let’s start with the code!
1. Only display one line of text and then hide and omit it
// Only display one line of text and then omit .element { width: 300px; /* Need to set a fixed width */ white-space: nowrap; /* Force single line display without line wrapping */ overflow: hidden; /* Hide the part beyond the box */ text-overflow: ellipsis; /* Display ellipses in excess */ }
2. Display the specified number of lines of text and then hide and omit it.
// Omit after displaying multi-line text.element { width: 300px; /* Need to set a fixed width */ display: -webkit-box; /* Use flexible box layout */ -webkit-box-orient: vertical; /* vertical arrangement */ -webkit-line-clamp: 3; /* Display three lines */ overflow: hidden; /* Hide the part beyond the box */ text-overflow: ellipsis; /* Display ellipses in excess */ }
Multi-line text is omitted by using display: -webkit-box;
flexible box layout and -webkit-line-clamp
to achieve multi-line text truncation.
Note: This method is suitable for WebKit core browsers (such as Chrome, Safari, etc.). For other browsers, additional polyfill support may be required.
Other solutions
1. Use JavaScript to dynamically calculate the height of text content and truncate it.
2. Use existing libraries: such as: Clamp.js
Clamp.js: A lightweight library for cross-browser multi-line text truncation.
//Single line $clamp(myHeader, {clamp: 1}); //Multiple lines $clamp(myHeader, {clamp: 3}); //Automatically calculate the number of rows based on available height $clamp(myParagraph, {clamp: 'auto'}); //Automatically calculate the number of lines based on the fixed height $clamp(myParagraph, {clamp: '35px'});
3. CSS Fallback (partial compatibility solution)
For some browsers, although there is no direct support for -webkit-line-clamp
attribute, we can combine some simple CSS to achieve an approximate effect.
.element { display: block; /* Display as block */ overflow: hidden; /* Hide excess content */ text-overflow: ellipsis; /* Display ellipses in excess */ line-height: 1.5em; /* Set line height */ max-height: 4.5em; /* Maximum height of 3 lines, 3 lines * 1.5 lines high = 4.5em */ white-space: normal; /* maintain normal text wrapping */ }
Although this scheme cannot achieve precise multi-line truncation in all cases, it is still suitable for supporting basic multi-line text omission display.
This concludes this article about hiding and displaying ellipses after CSS text exceeds the limit and other browser compatibility solutions. For more related CSS text exceeds the hidden content, please search previous articles on downcodes.com or continue to browse the related articles below. , I hope you will support downcodes.com more in the future!