Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't break words at whitespace with CSS

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!

enter image description here

like image 217
Ood Avatar asked Apr 07 '17 12:04

Ood


People also ask

How do you prevent text from breaking in CSS?

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).

How do I keep words together in CSS?

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.

Does CSS care about whitespace?

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.

Does CSS ignore 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.


1 Answers

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.

like image 99
mayersdesign Avatar answered Oct 27 '22 00:10

mayersdesign