How to prevent hyphenation using text overflow
P粉464208937
2023-09-03 15:00:49
<p>I'm trying to set a maximum number of lines for some titles, but the problem is that sometimes a line ends with a hyphen. What I need is that if a word has to be broken, it should be completely hidden and the ellipses placed after the previous word. </p>
<p>This code shows the problem: </p>
<p>
<pre class="brush:css;toolbar:false;">#head {
width:300px;
font-size: 20px;
display: -webkit-box !important;
color: #000000 !important;
text-overflow: ellipsis !important;
-webkit-line-clamp: 4 !important;
-webkit-box-orient: vertical !important;
overflow: hidden !important;
}</pre>
<pre class="brush:html;toolbar:false;"><!DOCTYPE html>
<html>
<div id="head">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a
</div>
</html></pre>
</p>
<p>There is a break in the word "ever", can I somehow prevent this from happening? </p>
To achieve the effect of completely hiding the word break and placing the ellipsis after the previous word, you can use JavaScript to manipulate the text content. Here is an example of how to modify the code to achieve this:
In this code, the JavaScript function
truncateText
is used to truncate the text content when it exceeds the specified maximum length. This function finds the last space character within the maximum length and replaces the remaining text with ellipses.You can adjust the
maxLength
parameter to the desired number of characters before adding the ellipsis.