CSS
Truncate Text with Ellipsis Inside a Flex Item
Learn how to correctly apply `text-overflow: ellipsis` to text within a flex item, preventing text from overflowing and ensuring a clean, truncated display.
<div class="flex-container">
<div class="icon">🔍</div>
<div class="text-content">
This is a very long piece of text that needs to be truncated with an ellipsis when it overflows its container in a flex layout.
</div>
<div class="action-button">▶</div>
</div>
<style>
.flex-container {
display: flex;
align-items: center;
border: 1px solid #ccc;
padding: 10px;
width: 300px; /* Fixed width to demonstrate truncation */
gap: 10px;
overflow: hidden; /* Important for ellipsis on children */
}
.icon {
flex-shrink: 0; /* Prevent icon from shrinking */
font-size: 1.5em;
}
.text-content {
flex-grow: 1; /* Allow text content to take available space */
flex-shrink: 1; /* Allow text content to shrink */
min-width: 0; /* CRITICAL: Allows flex item to shrink below content size */
white-space: nowrap; /* Prevent text from wrapping */
overflow: hidden; /* Hide overflowing content */
text-overflow: ellipsis; /* Display ellipsis for truncated text */
background-color: #e6f7ff;
padding: 5px;
}
.action-button {
flex-shrink: 0; /* Prevent button from shrinking */
padding: 5px 10px;
background-color: #007bff;
color: white;
border-radius: 4px;
cursor: pointer;
}
</style>
How it works: Applying `text-overflow: ellipsis` directly to a flex item often fails because flex items, by default, try to accommodate their content, even if it means overflowing the parent. The key to making ellipsis work within a flex item is setting `min-width: 0` (or `min-height: 0` for vertical truncation) on the flex item containing the text. This crucial property allows the flex item to shrink below its content's intrinsic width, enabling `overflow: hidden` and `text-overflow: ellipsis` to take effect. Additionally, `white-space: nowrap` prevents text wrapping before truncation.