如何通过CSS实现段落仅显示最多三行内容?
Hey there! Great question—your current approach with fixed height and overflow: hidden works, but it has a big downside: it’s not responsive. If your font size, line height, or container width changes, you might end up showing more or less than exactly 3 lines.
The far better solution is using CSS line clamping, which is purpose-built for truncating text to a specific number of lines. Here's how to implement it for your paragraph:
Step 1: Add the CSS Class
.truncate-3-lines { display: -webkit-box; -webkit-line-clamp: 3; /* Explicitly set to show 3 lines */ -webkit-box-orient: vertical; overflow: hidden; text-overflow: ellipsis; /* Optional: adds "..." to indicate truncated text */ }
Step 2: Apply the Class to Your Paragraph
<p class="truncate-3-lines">This is a long paragraph in HTML which you have in your web page but you can see only 3 lines of it. Add more text here to test the truncation—no matter how long the content gets, it will only display the first 3 lines and cut off cleanly (with an ellipsis if you included that property).</p>
Why This Is Superior to Fixed Height
- Responsive: Automatically adjusts to font size, line height, and container width—no manual height calculations needed.
- Semantic: No extra wrapping
divrequired; apply the class directly to your existing<p>tag. - User-Friendly: The optional
text-overflow: ellipsisgives users a clear visual cue that more content exists.
Browser Support
This method works in all modern browsers (Chrome, Firefox, Safari, Edge). While it uses -webkit- prefixes, these are still required for full cross-browser compatibility and don’t break functionality in supported browsers. For very old browsers like IE, you’d need a JavaScript fallback, but for most modern use cases, line clamping is the optimal choice.
内容的提问来源于stack exchange,提问作者Learner AKS

