如何实现固定宽高div多行文本溢出时末尾显示省略号?
Hey there! I see you're stuck trying to get multi-line text wrapping with ellipsis for overflow content—let's break down what's going wrong and fix it step by step.
Why Your Current Code Isn't Working
Your existing code has a conflicting property: white-space: nowrap forces the text to stay on a single line, which completely overrides the overflow-wrap: break-word behavior. Even if you remove nowrap, text-overflow: ellipsis only works for single-line text by default. That's why you're stuck with either no wrapping or no ellipsis.
The CSS Solution for Multi-Line Ellipsis
To get both automatic word wrapping and ellipsis for overflowing multi-line text, we'll use the -webkit-line-clamp property (supported by all modern browsers now, including Chrome, Safari, Edge, and Firefox 68+). Here's the corrected code:
<div style=" width: 400px; height: 50px; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 3; /* Adjust this number based on how many lines you want to show */ -webkit-box-orient: vertical; text-overflow: ellipsis; overflow-wrap: break-word; "></div>
Let's Break Down Each Property
display: -webkit-box: Sets the container to a flexible box layout required for-webkit-line-clampto function.-webkit-line-clamp: 3: Defines the maximum number of lines to display before truncating. Tweak this value to match yourheightsetting (for 50px height, 3 lines is a safe starting point).-webkit-box-orient: vertical: Ensures content flows vertically in lines—this is mandatory for-webkit-line-clampto work.overflow: hidden: Hides any text that exceeds the container's bounds.text-overflow: ellipsis: Adds the ellipsis at the end of the last visible line.overflow-wrap: break-word: Lets long words break onto the next line instead of overflowing the container.
Quick Compatibility Note
If you need to support very old browsers (like Firefox pre-68), you might need a JavaScript fallback to handle truncation. But for most modern use cases, the CSS above works perfectly.
内容的提问来源于stack exchange,提问作者hossein1976

