Hyphens and line breaking play a significant role in the presentation of text on the web. Hyphenation helps to improve the appearance of justified text, while line breaking determines how text wraps within its container. Let's explore these concepts in detail.
Hyphenation refers to the automatic insertion of hyphens in words to improve the appearance of justified text. It helps to distribute space more evenly between words, reducing large gaps between words and improving readability.
Line breaking determines how text wraps within its container when it reaches the end of a line. By default, browsers break lines at spaces or hyphens, but CSS provides properties to control line breaking behavior.
In CSS, we use the hyphens
property to control hyphenation and the word-break
property to control line breaking behavior.
/* Hyphenation */
p {
hyphens: auto;
}
/* Line Breaking */
p {
word-break: break-all;
}
Hyphens and Line Breaking Example
This is a longwordthatshouldbehyphenated properly.
In this example, we apply the hyphens: auto;
property to the <p>
element to enable automatic hyphenation. We also set word-break: break-all;
on the .text
class to force line breaks between any two characters.
Output: The long word in the paragraph will be hyphenated properly, and the text will break at any character if it exceeds the width of the container.
Let’s explore some advanced techniques for controlling hyphens and line breaking in CSS.
You can specify exceptions to hyphenation using the hyphenate-limit-chars
property
p {
hyphens: auto;
hyphenate-limit-chars: 6 3 3;
}
This will prevent hyphenation within words shorter than 6 characters and after the third and second characters of longer words.
The overflow-wrap
property allows you to control whether text should break at the end of a line or if it should overflow into the next line
p {
overflow-wrap: anywhere;
}
This allows text to break at any character within a word if necessary.
Let’s dive into some practical examples to solidify our understanding
p {
hyphens: auto;
}
.container {
width: 200px;
}
.text {
overflow-wrap: anywhere;
}
Hyphens and Line Breaking Practical Examples
This is a longwordthatshouldbehyphenated properly.
Thisisaverylongwordthatshouldbreakatanycharacterifnecessary.
Output: The HTML document will display examples of hyphenation in paragraphs and controlled line breaking within containers.
In this chapter, we've covered everything from the basics to advanced techniques of hyphens and line breaking in CSS. By understanding how to control hyphenation and line breaking behavior, you can create more readable and visually appealing text layouts on the web. Happy coding! ❤️