CSS text-overflow
The CSS text-overflow
property is used to control how text is displayed when it overflows the content box of an element, typically due to insufficient width to accommodate the entire text. It provides options for truncating or displaying an ellipsis (…) to indicate that there is more text than what is currently visible.
The text-overflow
property can only be used on block-level or inline-block elements and works in conjunction with the white-space
and overflow
properties.
Here are the possible values for the text-overflow
property:
clip
: The text that overflows the container is clipped, and the overflow is hidden. No ellipsis or other indication is shown, and the text is cut off.ellipsis
: The text that overflows the container is truncated and an ellipsis (…) is added at the end to indicate that the text has been cut off.string
: Allows you to define a custom string to be displayed at the end of the truncated text, instead of the default ellipsis (…).
Example:
.container {
width: 200px;
white-space: nowrap; /* Prevents the text from wrapping to multiple lines */
overflow: hidden; /* Hides the overflowed text */
text-overflow: ellipsis; /* Adds an ellipsis (...) at the end of the truncated text */
}
In this example, the text inside an element with the class .container
will be truncated and an ellipsis (…) will be added at the end if it overflows the container’s width of 200 pixels. The white-space: nowrap;
ensures that the text remains on a single line.
It’s important to note that the text-overflow
property only takes effect when the overflow
is set to hidden
and the white-space
is set to nowrap
. Additionally, text-overflow
may not work as expected if the element has explicit widths set, and the width is smaller than the actual content.
The text-overflow
property is commonly used in responsive designs, where you want to gracefully handle long text content in limited space. It provides a way to indicate to users that there is more text available, and they can interact with the content to view the full text, such as by hovering or clicking.