CSS Word Break Techniques
December 11, 2024 ยท AI Conversations
### Example CSS
.break-word {
word-wrap: break-word; /* Legacy support */
overflow-wrap: break-word; /* Modern browsers */
word-break: break-word; /* Optional for strict breaking */
}
### Explanation:
1. **`overflow-wrap: break-word;`**:
– Ensures words will wrap to the next line when they exceed the container width.
– Use this property for modern browsers.
2. **`word-wrap: break-word;`**:
– Provides similar behavior as `overflow-wrap` but for legacy browser support.
3. **`word-break: break-word;`** (Optional):
– Forces a break in the middle of a word when necessary, ideal for URLs or very long strings.
4. **Responsive Design Consideration**:
Use a media query to apply it only for smaller screens:
@media (max-width: 768px) {
.break-word {
word-wrap: break-word;
overflow-wrap: break-word;
}
}
### Applying It:
Add the `break-word` class to the element that contains the long word:
<div class="break-word">
ThisIsAReallyLongWordThatNeedsBreakingOnMobileDevices
</div>
This will ensure that the long word breaks properly on smaller screens, preventing layout overflow.
Break above like this Instandhaltungs-
service
### 1. **HTML Solution** (Soft Hyphen)
Insert the `` entity at the desired break point:
<p>Instandhaltungsservice</p>
– **How it works**:
The browser will break the word at `` if needed (e.g., on small screens). If there's enough space, the word remains unbroken.
—
### 2. **CSS Solution** (Hyphenation)
Use the `hyphens` property with proper language settings.
.break-hyphen {
hyphens: auto;
word-wrap: break-word;
overflow-wrap: break-word;
}
Set the language attribute for correct hyphenation:
<p class="break-hyphen" lang="de">Instandhaltungsservice</p>
– **How it works**:
The browser will automatically insert hyphens (`-`) at natural breakpoints based on the German language rules.
—
### 3. **Manual CSS Solution** (Forced Break with Hyphen)
To break exactly where you want (adding a visible hyphen):
.break-specific {
word-break: break-all;
}
Then, modify the HTML with a hidden hyphen:
<p class="break-specific">Instandhaltungs-<wbr>service</p>
– **“**: Suggests a break point for browsers.
### Final Recommendation
For the best user experience:
– Use **``** for a clean and semantic approach.
– Use **CSS hyphenation** for dynamic and multi-language content.