I’ve got a solution that should work in IE6 (and definitely works in 7+ & FireFox/Chrome).
You were on the right track using a span
, but the use of a ul
was wrong and the css wasn’t right.
Try this
<a class="htooltip" href="#">
Notes
<span>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin pharetra nonummy pede. Mauris et orci.
</span>
</a>
.htooltip, .htooltip:visited, .tooltip:active {
color: #0077AA;
text-decoration: none;
}
.htooltip:hover {
color: #0099CC;
}
.htooltip span {
display : none;
position: absolute;
background-color: black;
color: #fff;
padding: 5px 10px 5px 40px;
text-decoration: none;
width: 350px;
z-index: 10;
}
.htooltip:hover span {
display: block;
}
Everyone was going about this the wrong way. The code isn’t valid, ul
‘s cant go in a
‘s, p
‘s can’t go in a
‘s, div
‘s cant go in a
‘s, just use a span
(remembering to make it display
as a block
so it will wrap as if it were a div
/p
etc).
Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article
In this article, we will see how to wrap long text/word in a fixed-width span. The word-wrap property in CSS is used to break long words and wrap them into the next line. It defines whether to break words when the content exceeds the boundaries of its container.
Syntax:
word-wrap: normal|break-word|initial|inherit;
Example 1: The following code demonstrates the “normal” value for the word-wrap property. The text is broken which is shown by a border.
HTML
<!DOCTYPE html>
<
html
>
<
head
>
<
style
>
div
{
word-wrap:normal;
width: 150px;
border: 1px solid black;
}
</
style
>
</
head
>
<
body
>
<
h2
style
=
"color:green"
>GeeksforGeeks</
h2
>
<
div
>
GeeksforGeeks:AComputerSciencePortalForGeeks
</
div
>
</
body
>
</
html
>
Output:
Example 2: The following code demonstrates the “break-word” value for the word-wrap property. The text is broken which is shown in the next line inside the bordered box as it exceeds the given width.
HTML
<!DOCTYPE html>
<
html
>
<
head
>
<
style
>
div
{
word-wrap:break-word;
width: 150px;
border:1px solid black;
}
</
style
>
</
head
>
<
body
>
<
h2
style
=
"color:green"
>GeeksforGeeks</
h2
>
<
div
>
GeeksforGeeks:AComputerSciencePortalForGeeks
</
div
>
</
body
>
</
html
>
Output:
Like Article
Save Article
You can make the contents of HTML <p>, <div>, and <span> elements not to wrap by using some CSS. You need the white-space property. As we know, this property helps us to handle the spaces within the element.
So, if you want not to wrap the contents of the elements mentioned above, you need to use the “nowrap” value of the white-space property.
Example of making the content of the <p> element not to wrap:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
p {
white-space: nowrap;
}
</style>
</head>
<body>
<h1>White-space property example</h1>
<p>
Lorem Ipsum is simply dummy text.Lorem Ipsum is simply dummy text. Lorem Ipsum is simply dummy text. Lorem Ipsum is simply dummy text. Lorem Ipsum is simply dummy text. Lorem Ipsum is simply dummy text. Lorem Ipsum is simply dummy text. Lorem Ipsum is simply dummy text.
</p>
</body>
</html>
Result
Lorem Ipsum is simply dummy text.Lorem Ipsum is simply dummy text. Lorem Ipsum is simply dummy text. Lorem Ipsum is simply dummy text. Lorem Ipsum is simply dummy text. Lorem Ipsum is simply dummy text. Lorem Ipsum is simply dummy text. Lorem Ipsum is simply dummy text.
In the following example, in the same way, we make the content of the <div> element not to wrap. Also, we’ll add a border.
Example of making the content of the <div> element not to wrap:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
div {
white-space: nowrap;
border: 1px solid green;
}
</style>
</head>
<body>
<h1>White-space property example</h1>
<div>
Lorem Ipsum is simply dummy text.Lorem Ipsum is simply dummy text. Lorem Ipsum is simply dummy text. Lorem Ipsum is simply dummy text. Lorem Ipsum is simply dummy text. Lorem Ipsum is simply dummy text. Lorem Ipsum is simply dummy text.
</div>
</body>
</html>
In our last example, we’ll make the content of the <span> element not to wrap, again with the white-space property. We’ll set the display of the <span> to “block”, then, specify its width and border.
Example of making the content of the <span> element not to wrap:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
span {
display: block;
width: 250px;
border: 1px solid purple;
overflow: hidden;
white-space: nowrap;
}
</style>
</head>
<body>
<h1>White-space property example</h1>
<span>
Lorem Ipsum is simply dummy text.Lorem Ipsum is simply dummy text. Lorem Ipsum is simply dummy text. Lorem Ipsum is simply dummy text. Lorem Ipsum is simply dummy text. Lorem Ipsum is simply dummy text. Lorem Ipsum is simply dummy text.
</span>
</body>
</html>
Here, we also specified the overflow property with the “hidden” value, which allowed us to clip the content so as to fit the box.
CSS white-space is a property that gives you the ability to control the whitespace and line breaks in the text on a web page. As you might already know, whitespace on a text can be powerful from a creative point of view as well as from a purely formatting aspect. So, this is why it is important that you know how to use this property effectively in code.
Read on as we will explain it in great detail along with some code examples that you can use in your project.
Contents
- Possible Values for CSS White-space
- – Normal
- – Nowrap
- – Pre
- – Pre-wrap
- – Pre-line
- – Break-spaces
- Summary of CSS White-space values
- Possible Uses
- – Insert Line Breaks in Definition Lists
- – Typing Animation
- When Things Go Wrong
- – White-space Pre-line Extra Space
- – White-space: Pre Not Working as Expected
- – White-space Pre-wrap Not Working in Internet Explorer
- – White-space Nowrap With Ellipse
- CSS White-space vs Word-wrap
- Web Browser Support
- Conclusion
Possible Values for CSS White-space
The possible values for CSS white-space are:
- normal
- nowrap
- pre
- pre-wrap
- preline
- Break-spaces
In this first part of our article, we will be diving deeper into each of those values, so you fully understand each one’s scope.
– Normal
This is the default value, where the web browser will collapse a sequence of whitespace into a single one. Aso, if need be, the text will wrap into a new line.
The next HTML block has some whitespace, but when you view it in the web browser, they are all collapsed. Feel free to run this and see how it works:
<main>
<span class=”wrap-info”>
<code>white-space: normal</code>
</span>
<div class=”white-space-normal”>
<p>Lorem ipsum dolor sit amet, consectetur.
Ut enim ad minim veniam,
quis nostrud.
Duis aute irure dolor in reprehenderit in voluptate velit esse</p>
</div>
</main>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
display: grid;
place-items: center;
height: 100vh;
}
main {
width: 50%;
border: 5px solid #1560bd;
padding: 2em;
font-size: 1.2em;
line-height: 1.168;
position: relative;
}
.wrap-info {
position: absolute;
bottom: -3.2em;
left: -0.25em;
padding: 1em;
background-color: #1560bd;
color: #ffffff;
font-weight: bold;
}
.white-space-normal {
white-space: normal;
}
– Nowrap
With CSS white space nowrap, the web browser will collapse a good deal of whitespace into a single one. What’s more, the text will not wrap into a new line.
When you run the next code in your browser, you’ll observe that all the text appears on a single line. As a result, it leads to an overflow:
<main>
<span class=”wrap-info”>
<code>white-space: nowrap</code>
</span>
<div class=”white-space-nowrap”>
<p>Lorem ipsum dolor sit amet, consectetur.
Ut enim ad minim veniam,
quis nostrud.
Duis aute irure dolor in reprehenderit in voluptate velit esse</p>
</div>
</main>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
display: grid;
place-items: center;
height: 100vh;
}
main {
width: 50%;
border: 5px solid #c00;
padding: 2em;
font-size: 1.2em;
line-height: 1.168;
position: relative;
}
.wrap-info {
position: absolute;
bottom: -3.2em;
left: -0.25em;
padding: 1em;
background-color: #c00;
color: #ffffff;
font-weight: bold;
}
.white-space-nowrap {
white-space: nowrap;
}
– Pre
White-space: pre behaves like the
tag in HTML
. As a result, the web browser will preserve all the whitespace. The text will wrap if it contains a newline character or a line-break element like <br>.
Moreover, the next code demonstrates will help you understand how this works in a web browser. When you run the code, you’ll observe that all whitespace appears as it is in the HTML:
<main>
<span class=”wrap-info”>
<code>white-space: pre</code>
</span>
<div class=”white-space-pre”>
<p>Lorem ipsum dolor sit amet, consectetur.
Ut enim ad minim veniam,
quis nostrud.
Duis aute irure dolor in reprehenderit in voluptate velit esse</p>
</div>
</main>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
display: grid;
place-items: center;
height: 100vh;
}
main {
width: 50%;
border: 5px solid #321fb7;
padding: 2em;
font-size: 1.2em;
line-height: 1.168;
position: relative;
}
.wrap-info {
position: absolute;
bottom: -3.2em;
left: -0.25em;
padding: 1em;
background-color: #321fb7;
color: #ffffff;
font-weight: bold;
}
.white-space-pre {
white-space: pre;
}
– Pre-wrap
This is like white-space: pre, but the white-space pre-wrap text will wrap the text if required.
Now, when you run the next code block in your web browser, some text will wrap to a new line, even if it’s a single text:
<main>
<span class=”wrap-info”>
<code>white-space: pre-wrap</code>
</span>
<div class=”white-space-pre-wrap”>
<p>Lorem ipsum dolor sit amet, consectetur.
Ut enim ad minim veniam,
quis nostrud.
Duis aute irure dolor in reprehenderit in voluptate velit esse</p>
</div>
</main>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
display: grid;
place-items: center;
height: 100vh;
}
main {
width: 50%;
border: 5px solid #060223;
padding: 2em;
font-size: 1.2em;
line-height: 1.168;
position: relative;
}
.wrap-info {
position: absolute;
bottom: -3.2em;
left: -0.25em;
padding: 1em;
background-color: #060223;
color: #ffffff;
font-weight: bold;
}
.white-space-pre-wrap {
white-space: pre-wrap;
}
– Pre-line
White-space: pre-line will collapse a sequence of white space into a single one. Also, the text will wrap at line breaks, newline characters, and when it’s necessary.
The next code block will show you how white-space: pre-line works in a web browser, so check it out:
<main>
<span class=”wrap-info”>
<code>white-space: pre-line</code>
</span>
<div class=”white-space-pre-line”>
<p>Lorem ipsum dolor sit amet, consectetur.
Ut enim ad minim veniam,
quis nostrud.
Duis aute irure dolor in reprehenderit in voluptate velit esse</p>
</div>
</main>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
display: grid;
place-items: center;
height: 100vh;
}
main {
width: 50%;
border: 5px solid #060223;
padding: 2em;
font-size: 1.2em;
line-height: 1.168;
position: relative;
}
.wrap-info {
position: absolute;
bottom: -3.2em;
left: -0.25em;
padding: 1em;
background-color: #060223;
color: #ffffff;
font-weight: bold;
}
.white-space-pre-line {
white-space: pre-line;
}
– Break-spaces
This is like white-space: pre, with the following exceptions:
- All preserved white space will take up space, even at the end of the line
- White space preservation takes precedence over line break characters. Irrespective of the position of the whitespace character
- The preserved white space affect the box’s min-content size and max-content size
In the next HTML code, there is lots of space added so you can see how this particular value works on the web page:
<main>
<span class=”wrap-info”>
<code>white-space: break-spaces</code>
</span>
<div class=”white-space-break-spaces”>
<p>Lorem ipsum dolor sit amet, consectetur.
Ut enim ad minim veniam,
quis nostrud.
Duis aute irure dolor in reprehenderit in voluptate velit esse</p>
</div>
</main>
Summary of CSS White-space values
The table below is a summary of all CSS white space values and what happens when you use each one:
Text wrapping | Spaces and tabs | New lines | End-of-line spaces | |
normal | Wrap | Collapse | Collapse | Remove |
nowrap | No wrap | Collapse | Collapse | Remove |
pre | No wrap | Preserve | Preserve | Preserve |
pre-wrap | Wrap | Preserve | Preserve | Hang |
pre-line | Wrap | Collapse | Preserve | Remove |
break-spaces | Wrap | Preserve | Preserve | Wrap |
Possible Uses
You can use CSS white-space to create the following:
- Insert line breaks in definition list
- Typing animation
Let’s review each ouse-case so we can see how you can implement it in your code!
– Insert Line Breaks in Definition Lists
The elements of the definition list (<dt> and <dd>) are block-level elements. As a result, each of them will appear on a new line. Moreover, you can use white-space: pre to render the list in a presentable manner in the web browser:
<main>
<span class=”wrap-info”>
<code>White-space: Insert space in Definition List</code>
</span>
<dl class=”definition-list”>
<dt class=”definition-term”>Name</dt>
<dd class=”definition-description”>John Doe</dd>
<dt class=”definition-term”>Email</dt>
<dd class=”definition-description”>john.doe@no-mail.com</dd>
<dd class=”definition-description”>john.doe@no-mail.com</dd>
<dt class=”definition-term”>Location</dt>
<dd class=”definition-description”>127.0.0.1</dd>
</dl>
</main>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
display: grid;
place-items: center;
height: 100vh;
}
main {
width: 50%;
border: 5px solid #095a96;
padding: 2em;
font-size: 1.2em;
line-height: 1.168;
position: relative;
}
.wrap-info {
position: absolute;
bottom: -3.2em;
left: -0.25em;
padding: 1em;
background-color: #095a96;
color: #ffffff;
font-weight: bold;
}
.definition-term,
.definition-description {
display: inline;
}
.definition-description {
margin: 0;
font-weight: bold;
}
.definition-description + .definition-term::before {
content: ‘A’;
white-space: pre;
}
.definition-description + .definition-description::before {
content: ‘, ‘;
font-weight: normal;
}
– Typing Animation
In a typing animation, the text should appear on a single line without breaking into another line. This is achievable with the use of white-space: nowrap. Without it, the text will break into another line.
The next code block will show you how typing animation works in the web browser. Needless to say, white-space: nowrap plays a key role:
<div class=”typing-animation”>
<p>Typing animation</p>
</div>
body {
padding: 2em;
}
.typing-animation p {
font-size: 1em;
border-right: 0.5em solid #1560bd;
overflow: hidden;
width: 7.3em;
animation: typingAnimation 2s steps(40, end);
animation-fill-mode: forwards;
white-space: nowrap;
}
@keyframes typingAnimation {
0% {
width: 0;
}
99.9% {
border-right: 0.5em solid #1560bd;
}
100% {
border: none;
}
}
When Things Go Wrong
We took our time to identify some situations when white-space won’t work as expected. Also, we’ll discuss their potential solutions, which are:
- White-space pre-line extra space
- White-space pre not working as expected
- White-space pre-wrap not working in Internet Explorer
- White-space nowrap with ellipse
This happens when you have line breaks in your HTML code. Line-breaks can be newline characters (enter key on your keyboard) or HTML <br> elements.
So anytime you are using white-space: preline, look out for extra space at the top or bottom of the element in the HTML.
For example, in the next code block, there are four line breaks in the HTML. With white-space: pre-line, the web browser preserves the line breaks. As a result, the web browser will add unusual space at the top of the text:
<main>
<span class=”wrap-info”>
<code>white-space: pre-line extra space</code>
</span>
<div class=”white-space-pre-line”>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua.
</div>
</main>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
display: grid;
place-items: center;
height: 100vh;
}
main {
width: 50%;
border: 5px solid #060223;
padding: 2em;
font-size: 1.2em;
line-height: 1.168;
position: relative;
}
.wrap-info {
position: absolute;
bottom: -3.2em;
left: -0.25em;
padding: 1em;
background-color: #060223;
color: #ffffff;
font-weight: bold;
}
.white-space-pre-line {
white-space: pre-line;
}
– White-space: Pre Not Working as Expected
If a text contains many carriage returns and you want to display them on many lines, you can use white-space: pre. However, this will not work as expected. The fix is to use white-space: pre-line.
The next code shows how to do this, so all you have to do is change the white-space value to pre-line, and you’ll get each text on a new line:
<main>
<span class=”wrap-info”>
<code>white-space: pre not working</code>
</span>
<div class=”white-space-pre-not-working”>
<p>My name is John,
I am from Boston,
I am a Software Engineer.</p>
</div>
</main>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
display: grid;
place-items: center;
height: 100vh;
}
main {
width: 50%;
border: 5px solid #330ceb;
padding: 2em;
font-size: 1.2em;
line-height: 1.168;
position: relative;
}
.wrap-info {
position: absolute;
bottom: -3.2em;
left: -0.25em;
padding: 1em;
background-color: #330ceb;
color: #ffffff;
font-weight: bold;
}
.white-space-pre-not-working {
/**
* This will not work as intended.
white-space: pre; */
/**
* Instead, use pre-line
*/
white-space: pre-line;
}
– White-space Pre-wrap Not Working in Internet Explorer
At this point, we should mention that the CSS white space pre wrap works in Internet Explorer version eight and higher. Now that you know that, you can avoid possible errors!
– White-space Nowrap With Ellipse
CSS white-space: nowrap will cause all the text to appear on a single line, and so at times, you might truncate the text. If you want the truncated text to have an ellipse at the end, you can use the following CSS code:
.text-selector {
display: block;
width: 50%;
min-width: 1px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
The next code block is a full example that you can run in your web browser:
<main>
<span class=”wrap-info”>
<code>white-space: no-wrap on text</code>
</span>
<div class=”no-wrap-on-text”>
<p>My name is John,
I am from Boston,
I am a Software Engineer.</p>
</div>
</main>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
display: grid;
place-items: center;
height: 100vh;
}
main {
width: 50%;
border: 5px solid #431c97;
padding: 2em;
font-size: 1.2em;
line-height: 1.168;
position: relative;
}
.wrap-info {
position: absolute;
bottom: -3.2em;
left: -0.25em;
padding: 1em;
background-color: #431c97;
color: #ffffff;
font-weight: bold;
}
.no-wrap-on-text p {
display: block;
width: 50%;
min-width: 1px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
CSS White-space vs Word-wrap
CSS white-space and its values control white space in a text. Word-wrap allows you to break an unbreakable long string into a new line. An “unbreakable long string” means the text should not have any spaces in it.
The next code block shows how word-wrap works in a web browser, so all you have to do is run the code and observe what happens. Also, when you delete the word-wrap from the CSS code, the text will overflow its container:
<main>
<span class=”wrap-info”>
<code>white-space vs word-wrap</code>
</span>
<div class=”white-space-word-wrap”>
<p>Theisisanunbreakabletext.Theisisanunbreakabletext.Theisisanunbreakabletext.Theisisanunbreakabletext.Theisisanunbreakabletext.</p>
</div>
</main>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
display: grid;
place-items: center;
height: 100vh;
}
main {
width: 50%;
border: 5px solid #3677f4;
padding: 2em;
font-size: 1.2em;
line-height: 1.168;
position: relative;
}
.wrap-info {
position: absolute;
bottom: -3.2em;
left: -0.25em;
padding: 1em;
background-color: #3677f4;
color: #ffffff;
font-weight: bold;
}
.white-space-word-wrap {
width: 200px; /* This will restrict the text */
}
p {
/*white-space: nowrap;*/
word-wrap: break-word;
}
Web Browser Support
All modern web browsers support CSS white-space property.
Conclusion
At this stage, you’ve learned a lot about CSS white-space, and when you can use it. Here is a summary of everything that you’ve learned in the article:
- You can use CSS white-space to control the white space in your text
- CSS white-space property accepts values such as nowrap, pre, pre-wrap, pre-line, and break-spaces
- You can use CSS white-space to create a typing animation. Also, you can use it to insert line breaks in HTML definition lists
- CSS white-space is different from word-wrap; CSS white-space controls whitespace, whereas word-wrap will break an unbreakable string into a new line
- CSS white-space works in Internet Explorer eight and above
CSS white-space gives you more control over the whitespace in your text. Now that you know everything there is to know about it, you are all prepared to handle any whitespace insertions on your web pages.
- Author
- Recent Posts
Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team
Перенести ли текст автоматически или показать в одну строку, отобразить рядомстоящие пробелы как один или каждый в отдельности определяет white-space
[w3.org].
white-space
-
normal
- текст переносится | пробелы не учитываются | Enter (разрыв строки) не учитывается
-
pre-line
- текст переносится | пробелы не учитываются | Enter учитывается
-
pre-wrap
- текст переносится | пробелы учитываются | Enter учитывается
-
pre
- текст не переносится | пробелы учитываются | Enter учитывается
-
nowrap
- текст не переносится | пробелы не учитываются | Enter не учитывается
-
initial
normal
-
inherit
- наследует значение родителя
-
unset
- наследует значение родителя
ноль один два три Enter
пять шесть семь восемь девять десять одиннадцать двенадцать тринадцать четырнадцать
<style> div { white-space: normal; border: 1px solid red; } </style> <div>ноль один два три <kbd>Enter</kbd> пять шесть семь восемь девять десять одиннадцать двенадцать тринадцать четырнадцать</div>
У тега <pre>
по умолчанию white-space
имеет значение pre
.
Значения, отличные от normal
, часто применяются
- в комментариях, которые заполняют посетители, далёкие от HTML. Абзацы разбиваются не тегом
<p>
, а перевод строки обозначается не тегом<br>
, а символом - для демонстрации HTML кода.
- для оформления стихов.
Запретить перенос
Значения pre-wrap и pre-line поддерживаются Internet Explorer 8
Запрет переноса с помощью white-space: nowrap;
<style> .nowrap { white-space: nowrap; } </style> Значения <span class='nowrap'>pre-wrap</span> и <span class='nowrap'>pre-line</span> поддерживаются <span class='nowrap'>Internet Explorer 8</span>
Запрет переноса с помощью неразрывного пробела
и/или неразрывного дефиса ‑
В данном примере они более подходят, так как занимают меньше места. К тому же при использовании overflow-wrap: break-word;
или word-wrap: break-word;
или word-break: break-all;
символы всё же в определённый момент переходят на следующую строчку.
Значения pre‑wrap и pre‑line поддерживаются Internet Explorer 8
Прокрутка при отключении автопереноса
Часто совместно со значениями pre
или nowrap
элементу меняется значение свойства overflow
, чтобы добавить полосу прокрутки или обрезать выходящую за границу часть, дабы не появился горизонтальный скролл у всего сайта.
<style> div { width: 50%; border: 1px solid red; white-space: nowrap; } div:nth-child(2) { overflow: hidden; } div:nth-child(3) { overflow-x: scroll; } div:nth-child(4) { overflow: auto; } </style> overflow: visible; <div>Значения pre-wrap и pre-line поддерживаются IE 8</div> overflow: hidden; <div>Значения pre-wrap и pre-line поддерживаются IE 8</div> overflow-x: scroll; <div>Значения pre-wrap и pre-line поддерживаются IE 8</div> overflow: auto; <div>Значения pre-wrap и pre-line поддерживаются IE 8</div>
Разрыв строки
Тег <br>
Элементы после тега <br>
будут перенесены на следующую строку с любым значением свойства white‑space
.
ноль один <br>
три Enter
пять шесть
<style> div { white-space: nowrap; border: 1px solid red; } </style> <div>ноль один <code><br></code><br> три <kbd>Enter</kbd> пять шесть</div>
Блочный элемент
Всё содержимое блочного элемента будет перенесено на отдельную строку с любым значением свойства white‑space
.
ноль один
<div></div>
три Enter
пять шесть
<style> #raz { white-space: nowrap; border: 1px solid red; } </style> <div id="raz">ноль один <div><code><div></div></code></div> три <kbd>Enter</kbd> пять шесть</div>
Свойство white-space
<style> h1 { white-space: pre-line; } span { padding: 0 .5em; background: black; color: #fff; } </style> <h1>Это должно быть сверху <span>это под ним</span></h1>
Разрыв строки в псевдоэлементах ::before
/::after
<style> div::after { content: "A Номер: 1 A Год: 2017"; white-space: pre; } </style> <div>Текст</div>
У моноширинного шрифта все символы одной ширины, в том числе пробел
¶¶¶¶¶¶¶¶¶¶¶
¶¶¶¶¶ ¶¶¶¶¶¶
¶¶¶¶ ¶¶¶¶¶¶¶¶¶¶¶¶
¶¶ ¶¶¶ ¶¶¶¶¶¶¶
¶¶ ¶¶ ¶¶¶¶¶¶¶¶
¶¶ ¶¶¶¶ ¶ ¶¶
¶¶ ¶0 ¶ ¶¶ ¶¶¶¶¶¶¶
¶¶ ¶ ¶¶¶¶ ¶¶ ¶¶
¶¶ ¶ ¶¶¶¶¶¶¶¶¶¶¶ ¶ ¶ ¶¶
¶¶ ¶¶¶¶¶¶¶¶¶¶ ¶¶ ¶ ¶ ¶¶ ¶ ¶¶
¶¶¶¶¶¶¶ ¶ ¶¶ ¶ ¶ ¶¶¶ ¶ ¶
¶ ¶¶¶¶¶ ¶ ¶¶¶¶ ¶¶ ¶¶
¶ ¶¶¶¶¶¶ ¶ ¶ ¶¶¶¶¶¶ ¶
¶¶¶¶¶ ¶ ¶ ¶ ¶¶¶¶¶ ¶¶
¶¶¶ ¶¶ ¶ ¶¶¶¶ ¶¶¶¶¶ ¶¶
¶ ¶ ¶¶ ¶¶¶ ¶¶¶¶ ¶
¶¶¶¶ ¶ ¶¶ ¶¶¶ ¶
¶¶¶¶¶ ¶ ¶¶¶¶ ¶¶
¶ ¶¶¶ ¶¶
¶¶¶¶¶ ¶¶
¶¶¶¶ ¶¶
¶¶¶¶ ¶¶
¶ ¶ ¶
¶ ¶
¶¶ ¶¶
¶¶¶¶¶¶ ¶¶¶¶
¶¶ ¶¶¶¶
¶¶ ¶¶¶
¶¶ ¶ ¶¶¶ ¶¶
¶¶ ¶¶ ¶¶¶¶ ¶¶
¶¶ ¶
¶ ¶
¶¶
<style> div { white-space: pre; overflow: auto; font-family: monospace; line-height: normal; } </style> <div>Дельфин из символов</div>
This guide explains the various ways in which overflowing text can be managed in CSS.
What is overflowing text?
In CSS, if you have an unbreakable string such as a very long word, by default it will overflow any container that is too small for it in the inline direction. We can see this happening in the example below: the long word is extending past the boundary of the box it is contained in.
CSS will display overflow in this way, because doing something else could cause data loss. In CSS data loss means that some of your content vanishes. So the initial value of overflow
is visible
, and we can see the overflowing text. It is generally better to be able to see overflow, even if it is messy. If things were to disappear or be cropped as would happen if overflow
was set to hidden
you might not spot it when previewing your site. Messy overflow is at least easy to spot, and in the worst case, your visitor will be able to see and read the content even if it looks a bit strange.
In this next example, you can see what happens if overflow
is set to hidden
.
Finding the min-content size
To find the minimum size of the box that will contain its contents with no overflows, set the width
or inline-size
property of the box to min-content
.
Using min-content
is therefore one possibility for overflowing boxes. If it is possible to allow the box to grow to be the minimum size required for the content, but no bigger, using this keyword will give you that size.
Breaking long words
If the box needs to be a fixed size, or you are keen to ensure that long words can’t overflow, then the overflow-wrap
property can help. This property will break a word once it is too long to fit on a line by itself.
Note: The overflow-wrap
property acts in the same way as the non-standard property word-wrap
. The word-wrap
property is now treated by browsers as an alias of the standard property.
An alternative property to try is word-break
. This property will break the word at the point it overflows. It will cause a break-even if placing the word onto a new line would allow it to display without breaking.
In this next example, you can compare the difference between the two properties on the same string of text.
This might be useful if you want to prevent a large gap from appearing if there is just enough space for the string. Or, where there is another element that you would not want the break to happen immediately after.
In the example below there is a checkbox and label. Let’s say, you want the label to break should it be too long for the box. However, you don’t want it to break directly after the checkbox.
Adding hyphens
To add hyphens when words are broken, use the CSS hyphens
property. Using a value of auto
, the browser is free to automatically break words at appropriate hyphenation points, following whatever rules it chooses. To have some control over the process, use a value of manual
, then insert a hard or soft break character into the string. A hard break (‐
) will always break, even if it is not necessary to do so. A soft break (­
) only breaks if breaking is needed.
You can also use the hyphenate-character
property to use the string of your choice instead of the hyphen character at the end of the line (before the hyphenation line break).
This property also takes the value auto
, which will select the correct value to mark a mid-word line break according to the typographic conventions of the current content language.
The <wbr>
element
If you know where you want a long string to break, then it is also possible to insert the HTML <wbr>
element. This can be useful in cases such as displaying a long URL on a page. You can then add the property in order to break the string in sensible places that will make it easier to read.
In the below example the text breaks in the location of the <wbr>
.
See also
- The HTML
<wbr>
element - The CSS
word-break
property - The CSS
overflow-wrap
property - The CSS
white-space
property - The CSS
hyphens
property - Overflow and Data Loss in CSS
- This topic is empty.
Viewing 9 posts — 1 through 9 (of 9 total)
-
Posts
-
November 16, 2013 at 10:27 pm
#156282
http://stagedecommerce.webeclectic.com/
I’ve tried different white-space and word-break properties. How can I get the text on these paragraphs to avoid hyphened word breaks and have the text center justified. Center justified meaning not only text aligned center but actually justified.
November 16, 2013 at 10:50 pm
#156284
__
Participant
How can I get the text on these paragraphs to avoid hyphened word breaks …?
‑
(copy+paste:‑
) is the non-breaking-hyphen entity. AFAIK browser support is solid, though it may vary in appearance depending on the font used (most fonts don’t include this character, so you may see system substitutions).You can also use CSS:
<span style="white-space: nowrap">no-breaks-here</span>
Center justified meaning not only text aligned center but actually justified.
Could you explain further…? “Centered” and “justified” are mutually exclusive concepts.
November 17, 2013 at 12:17 am
#156289
__
Participant
http://jknetdesign.com/images/bluopal-forum.png
Both columns (except the list) in that shot are justified, not centered.
The last line aligning left is normal behavior; there are semi-hacks to justify the last line. FireFox and IE also support the
text-align-last
property (webkit may jump onboard eventually, I think it’s an up-and-coming spec) if you want the last line right-justified or centered.This a WordPress theme so I am depending on CSS. I tried nowrap and the text spread across the entire page…
You would have to change the markup. Either by replacing the character itself, or by wrapping the text-in-question in a span before applying
nowrap
.November 17, 2013 at 2:13 pm
#156335
__
Participant
I added a span class called nobreak and wrapped the paragraphs and it’s all across the screen.
You misunderstand: don’t wrap the paragraphs (unless you want them all across the screen). Wrap the words that you don’t want to break.
<p>This is my paragraph. It will wrap normally, except for the part about <span style="white-space:nowrap">happily-hyphenated-hillbillies</span>.
Having justified text is going to be a nightmare on a responsive site — or with narrow columns.
Yeah. At the very least, make sure any justified text is in a container with a minimum width.
November 17, 2013 at 3:11 pm
#156340
__
Participant
Why would I wrap each compromised word when I can just add a br tag?
I’m not sure I understand. You would wrap the individual words so the
nowrap
property applies only to them, rather than to the entire text (which, I gather, is not what you want).How would adding a
<br>
tag help prevent line breaks?make sure any justified text is in a container with a minimum width
That’s what I was looking for! I knew there was another property needed to assist the nowrap.
That suggestion was meant to for the “ugly-justified-text-in-narrow-columns” issue. It doesn’t affect text wrapping at all.
June 1, 2015 at 4:44 am
#203031
It’s quite a while since this was asked, but, anyway, maybe somebody finds it. What jknetdesign was looking for, I think, is:
-webkit-hyphens: none;
-moz-hyphens: none;
hyphens: none;Good day.
June 2, 2015 at 8:10 am
#203093
I didn’t about the hyphens rule.
Thanks
June 2, 2015 at 8:21 am
#203094
April 30, 2017 at 5:43 am
#254347
I found it! Thanks, did the trick.
-
Author
Posts
Viewing 9 posts — 1 through 9 (of 9 total)
- The forum ‘CSS’ is closed to new topics and replies.
Note: This article is focused on the semantics of the English Language as the Writing System. Other systems, especially CJK (Chinese Japanese Korean) have conventions and overflow requirements that vary from English and are out of the scope of this article.
Text Wrapping
In CSS, overflow is the scenario when the content inside a fixed-width container, is wider than the container’s width. The default behavior of CSS is to render the content flowing out of the container. This may look ugly but this helps the developer see the issue and fix it — instead of the issue getting hidden which can cause potential missing information for the user. For example, a form submission button overflowing and becoming inaccessible. So to avoid such issues, CSS by default prevents Data Loss.
Content overflowwwwwwwwwww
CSS offers multiple capabilities to fix this issue.
Property: overflow-wrap (alias word-wrap)
This property applies to inline elements. It determines whether the browser should break an otherwise unbreakable string to avoid it from overflowing its parent’s width.
It has the following possible keyword values.
- normal
- Anywhere
- break-word
overflow-wrap: normal
When set to normal, the browser will break the string on default/natural opportunities, such as a blank space or a hyphen (‘-’) character. It will also leverage soft-hyphen entity ­
to break.
This is the initial value of the overflow-wrap
property. So by default, every string will be broken at soft wrap opportunities, if any, on overflow.
This is how ‘ContentOverflowing’ and ‘Content-Overflowing’ will be handled.
ContentOverflowing
Content-Overflowing
overflow-wrap: anywhere;
This value allows the browser to break the string anywhere to avoid overflow.
Consider the following scenario with the default overflow-wrap: normal;
value for a fixed-width container.
ContentOverflow
There is no blank space, a hyphen, or any other soft wrap opportunity in the string. Therefore, it overflows. If we apply overflow: anywhere;
, we get the following, wrapped result.
ContentOverflow
overflow-wrap: break-word;
It behaves the same as overflow-wrap: anywhere;
. The difference is that the former does not consider soft-wrap opportunities when calculating min-content intrinsic sizes. In case you have not explored extrinsic vs intrinsic sizing, Ahmed Shadeed provides a great resource. It breaks only those words which have a width smaller than the available width.
Content is Overflowing
Property: word-break
CSS offers another property, word-break for handling the same issue — overflows.
It has the following keyword values
- normal
- break-all
- keep-all
- break-word
word-break: normal;
Words will break at the default rules — such as a blank space, a hyphen, etc.
This is how ‘ContentOverflow’ and ‘Content-Overflow’ will be handled.
ContentOverflow
Content-Overflow
word-break: break-all;
Break the word at the point it overflows. It does not take into account if placing the overflowing word onto the next line will eliminate the overflow in the first place or not. This doesn’t apply to CJK writing systems.
ContentOverflow
word-break: keep-all;
For Non-CJK systems, the behavior is the same as word-break: normal
.
ContentOverflow
word-break: break-word;
It has the same effect that word-break: normal;
and overflow-wrap: anywhere;
has. But unlike word-break: break-all;
, it takes into account if placing the overflowing word onto the next line will eliminate the overflow.
For example, let’s see how word-break: break-word;
handles the following scenario:
Content is Overflowing Again
We observe that the whole word ‘Overflowing’ was moved onto the next line instead of breaking as it can fit the available width without overflowing. If we apply word-break: break-all;
to it, this is what we get:
Content is Overflowing Again
The word ‘Overflowing’ was broken at exactly the point where it otherwise caused the overflow. And it was not considered if moving it onto the next line eliminated the overflow or not.
overflow-wrap vs word-break
At a high level, both properties solve the same issue. But, a key difference lies in how both the properties approach the issue and the subtle aesthetic variation in their outcomes.
To visualize, consider a fixed and short-width container for the test “A Very LongWordThatHasNoBreakingPossibilities”.
A Very LongWordThatHasNoBreakingPossibilities
Let’s solve the overflow with overflow-wrap: break-word;
.
A Very LongWordThatHasNoBreakingPossibilities
Now, let’s solve it with word-break: break-all;
.
A Very LongWordThatHasNoBreakingPossibilities
Notice the difference? word-break: break-all;
breaks the word even if placing the word on the next line would eliminate the need for breaking. This prevents large gaps before the breaks — and produces visually better results. The difference is more clearly visible in the overflow-wrap: anywhere;
vs word-break: break-all;
case. A case of the apparently twin properties. Consider you have a very short space to squeeze in a checkbox and a text which can not fit on the same line without overflowing. This is how the outcome looks like with overflow-wrap: anywhere;
:
Photosynthesis
We observe that a lot of real estate beside the checkbox has been left unutilized. A better fix is provided by word-break: break-all;
:
Photosynthesis
As observed, word-break
discards the possibility of the word fitting the next line and prefers optimizing the usage of available real estate — this is often the better adjustment visually.
The above example receives its inspiration from MDN’s resource on text wrapping.
Summary
Property | Value | Behavior | When To Use | Example |
---|---|---|---|---|
overflow-wrap |
|
Break at natural line breakpoints such as blank space, a hyphen | When overflow is determined to not be a possibility |
Content |
anywhere |
Break between any 2 characters where the overflow occurs and consider soft wrap opportunities when calculating the min-content intrinsic sizes | When overflow should be handled by breaking long words. As discussed, the alternative option of word-break: break-all; produces visually better results |
ContentOverflow |
|
break-word |
Break between any 2 characters but do not consider soft wrap opportunities when calculating the min-content intrinsic sizes | When overflow should be handled by breaking only those words which have a width smaller than the available width |
Content is Overflowing |
|
word-break |
normal |
Break at default rules | When overflow is determined to not be a possibility |
Content |
break-all |
Break exactly where the content overflows | When overflow should be handled by breaking text exactly at the point of overflow — even if placing the word on a new line eliminates the overflow |
Content is Overflowing Again |
|
break-word |
Same as word-break: normal; and overflow-wrap: anywhere; — Break can create gaps unlike word-break: break-all; |
When placing the overflowing word onto the next line eliminates overflow. This can cause gaps. |
Content is Overflowing Again |
Examples
Here are examples from the above summary in a codepen to help demonstrate what the CSS code should look like:
<section class="centered"> <h2>Without Handling Overflow</h2> <div>Content with aVeryVeryVeryLongWord</div> <!----> <h2>Handling Overflow with overflow-wrap</h2> <h3>overflow-wrap: normal;</h3> <div class="ow-normal">Content with aVeryVeryVeryLongWord</div> <h3>overflow-wrap: anywhere;</h3> <div class="ow-anywhere">Content with aVeryLongWordThatDoesNotFit</div> <h3>overflow-wrap: break-word;</h3> <div class="ow-break-word">Content with aVeryLongWordThatDoesNotFit</div> <!----> <h2>Handling Overflow with word-break</h2> <h3>word-break: normal;</h3> <div class="wb-normal">Content with aVeryVeryVeryLongWord</div> <h3>word-break: break-all;</h3> <div class="wb-break-all">Content with aVeryLongWordThatDoesNotFit</div> <h3>word-break: break-word;</h3> <div class="wb-break-word">Content with aVeryLongWordThatDoesNotFit</div> </section>
* { font-family: sans-serif; } section.centered { text-align: center; } div { display: inline-block; width: 130px; border: 3px solid #48abe0; text-align: left; } .ow-normal { overflow-wrap: normal; } .ow-anywhere { overflow-wrap: anywhere; } .ow-break-word { overflow-wrap: break-word; } .wb-normal { word-break: normal; } .wb-break-all { word-break: break-all; } .wb-break-word { word-break: break-word; } h3 { font-weight: normal; font-style: italic; border-top: 1px solid #b5b5b5; width: 30%; margin-left: auto; margin-right: auto; margin-top: 20px; padding-top: 20px; }
Conclusion
This article has scratched the surface of text-wrapping. Wrapping in itself is a deeper topic as it is tightly coupled to the semantics of the target language. Moreover, it is becoming common to offer web content in multiple languages — aka Internatiolaisation/ Localisation — which makes learning it more important than before for the developers.