I have a div with a set width. The way text is broken by default is at a white space. Is there any way to set the style of my element, so that the text is broken at any given character to fill out the maximum space available?
Thanks in advance!
If you want to prevent the text from wrapping, you can apply white-space: nowrap; Notice in HTML code example at the top of this article, there are actually two line breaks, one before the line of text and one after, which allow the text to be on its own line (in the code).
The secret code To force a web browser to treat 2 separate words as if they were 1, use the code instead of a space, like so: These two words are like one.
Yes, the whitespace here does matter. Typically spaces don't matter, but CSS functions are sensitive like that. Here's what the MDN says: Note: The + and - operators must always be surrounded by whitespace.
How does CSS process whitespace? Most whitespace characters are ignored, not all of them are. In the earlier example one of the spaces between "Hello" and "World!" still exists when the page is rendered in a browser.
The word-break property in CSS can be used to change when line breaks ought to occur. Normally, line breaks in text can only occur in certain spaces, like when there is a space or a hyphen. But using word-break: break-all
we can override that.
As an aside this can be very useful for stopping long urls from breaking out of text containers.
div {
width: 200px;
background: pink;
}
p {word-break: break-all; }
<div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum venenatis, justo quis mollis volutpat, nibh enim. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum venenatis, justo quis mollis volutpat, nibh enim</p>
</div>
jQuery "alternative"
Plugins including, but not limited to, https://github.com/bramstein/hypher can also be employed and will likely give a nicer overall appearance by using associated dictionaries (language dependent) to hyphenate the words properly when they break.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With