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

如何实现固定宽高div多行文本溢出时末尾显示省略号?

Fixing Multi-Line Text Ellipsis with Automatic Word Wrapping

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-clamp to function.
  • -webkit-line-clamp: 3: Defines the maximum number of lines to display before truncating. Tweak this value to match your height setting (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-clamp to 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 17:52:34