移动端Safari下如何实现两个Div各自最大3行且总行数不超过5行的文本截断(带省略号)?
Solution for Combined Line-Limit Truncation on Mobile Safari
Great question! This is a common tricky scenario when dealing with text truncation, and luckily we can pull this off with pure CSS that works perfectly on mobile Safari—no JavaScript required. Here's how to implement it:
Core Idea
We’ll use a combination of flexbox for vertical spacing control, -webkit-line-clamp for per-element truncation, and a fixed max-height on the parent container to enforce the total 5-line limit.
Step-by-Step Implementation
First, define your HTML structure:
<div class="content-container"> <div class="title">Your long or short title text goes here...</div> <div class="description">Your even longer description text that might need truncating goes here...</div> </div>
Then add the following CSS (tailor the line-height and spacing to match your design):
/* Parent container: Enforces total 5-line limit */ .content-container { line-height: 1.5; /* Consistent line height for accurate height calculations */ max-height: calc(1.5em * 5 + 0.5em); /* 5 lines total + 0.5em spacing between title/description */ overflow: hidden; display: flex; flex-direction: column; } /* Title: Max 3 lines */ .title { display: -webkit-box; -webkit-box-orient: vertical; /* autoprefixer: off */ /* Prevents tools from removing this critical property */ -webkit-line-clamp: 3; overflow: hidden; flex: 0 1 auto; /* Allows title to shrink if needed, but caps at 3 lines */ margin-bottom: 0.5em; /* Spacing between title and description */ } /* Description: Max 3 lines, but constrained by remaining space */ .description { display: -webkit-box; -webkit-box-orient: vertical; /* autoprefixer: off */ -webkit-line-clamp: 3; overflow: hidden; flex: 1; /* Takes up remaining space in the container */ }
How It Works
- Parent Container: The
max-heightis calculated to exactly fit 5 lines of text plus the spacing between title and description. This ensures the total content never exceeds your desired line count. - Title: The
-webkit-line-clamp: 3ensures it never shows more than 3 lines. Theflex: 0 1 autolets it take up only the space it needs (up to 3 lines). - Description: It uses
-webkit-line-clamp: 3to cap its own line count at 3, but since the parent container's total height is limited, if the title uses all 3 lines, the description will only have space for 2 lines—automatically truncating with an ellipsis.
Key Notes for Mobile Safari
-webkit-line-clampis fully supported on mobile Safari (and all WebKit-based browsers).- The
/* autoprefixer: off */comment is important: some CSS optimization tools will strip-webkit-box-orient: verticalunless you add this guard. - Keep your
line-heightconsistent across all elements to ensure themax-heightcalculation is accurate.
内容的提问来源于stack exchange,提问作者Can Poyrazoğlu
相关产品推荐
相关产品推荐

