You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过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 div required; apply the class directly to your existing <p> tag.
  • User-Friendly: The optional text-overflow: ellipsis gives 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:44:49