CSS3 has brought in several new properties for modifying text content. However, some of these properties have been around for a while. These properties offer precise control over how text is displayed in web browsers.
Text can overflow when it's prevented from wrapping. For instance, if the white-space
property is set to nowrap
for the containing element, or if a single word, like a long email address, is too lengthy to fit in the available space. In such cases, CSS3's text-overflow
property comes in handy to decide how the overflowed text content should be handled.
You have options to display or clip the overflowed text. Additionally, you can choose to display an ellipsis (...) or a custom string instead of the clipped text to inform the user.
Accepted values for the word-break
property include: clip
, ellipsis
, and string
.
p {
width: 400px;
overflow: hidden;
white-space: nowrap;
background: #cdcdcd;
}
p.clipped {
text-overflow: clip; /* clips the overflowed text */
}
p.ellipses {
text-overflow: ellipsis; /* displays '…' to represent clipped text */
}
Warning: The string
value for the text-overflow
property isn't widely supported in web browsers. It's better to avoid using it.
You can also break a lengthy word and force it to wrap onto a new line that exceeds the boundaries of the containing element using the CSS3 word-wrap
property.
Accepted values for the word-wrap
property include: normal
and break-word
.
p {
width: 200px;
background: #ffc4ff;
word-wrap: break-word;
}
Tip: Refer to individual property references for all possible values and browser support for these CSS properties.
You can also define the line breaking rules for text (i.e., how lines within words should break) using the CSS3 word-break
property.
Accepted values for the word-break
property include: normal
, break-all
, and keep-all
.
p {
width: 150px;
padding: 10px;
}
p.break {
background: #bedb8b;
word-break: break-all;
}
p.keep {
background: #f09bbb;
word-break: keep-all;
}