Handling Text Overflow with CSS `text-overflow`: Displaying Overflow Indicators
Learn how to use CSS's `text-overflow` property to manage text that overflows its container. This tutorial explains the `text-overflow` property's values (clip, ellipsis, string), their effects, and how to use them in conjunction with `white-space: nowrap;` and `overflow: hidden;` to create visually appealing and informative text displays.
Handling Text Overflow with CSS `text-overflow`
Understanding `text-overflow`
The CSS `text-overflow` property controls how text that overflows its containing element is displayed. It provides a way to indicate to the user that there is more text than is currently visible. The `text-overflow` property doesn't work on its own; you must also use `white-space: nowrap;` (to prevent text wrapping) and `overflow: hidden;` (to hide overflowing text) for it to have any effect.
`text-overflow` Property Values
clip
(default): The overflowing text is simply clipped (cut off) at the container's edge.ellipsis
: An ellipsis (three dots "...") is displayed to indicate that the text has been truncated.string
: A custom string is displayed to show the truncation. Note: Browser support for this value is limited (primarily Firefox).initial
: Resets the property to its default value (clip
).inherit
: Inherits the `text-overflow` value from its parent element.
`text-overflow` Syntax
The syntax is:
text-overflow: clip | ellipsis | string | initial | inherit;
Examples of `text-overflow`
These examples demonstrate the different `text-overflow` values. You would need to include corresponding HTML elements (a container with a defined width and text that overflows) and apply the CSS to see the effects. The `text-overflow` property is applied to the container element.
Example 1: `clip` and `ellipsis`
This shows the basic difference between clipping and showing an ellipsis. Both require `white-space: nowrap;` and `overflow: hidden;` on the container to work correctly.
CSS Code
.container {
width: 150px;
white-space: nowrap;
overflow: hidden;
}
.container.ellipsis {
text-overflow: ellipsis;
}
Example 2: `ellipsis` and `inherit`
This shows how `text-overflow: inherit;` on a child element takes its value from its parent.
CSS Code
.container {
width: 150px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.container p {
text-overflow: inherit;
}