The white-space
CSS property sets how white space inside an element is handled.
Try it
The property specifies two things:
- Whether and how white space is collapsed.
- Whether lines may wrap at soft-wrap opportunities.
Syntax
/* Keyword values */
white-space: normal;
white-space: nowrap;
white-space: pre;
white-space: pre-wrap;
white-space: pre-line;
white-space: break-spaces;
/* Global values */
white-space: inherit;
white-space: initial;
white-space: revert;
white-space: revert-layer;
white-space: unset;
The white-space
property is specified as a single keyword chosen from the list of values below.
Values
normal
-
Sequences of white space are collapsed. Newline characters in the source are handled the same as other white space. Lines are broken as necessary to fill line boxes.
nowrap
-
Collapses white space as for
normal
, but suppresses line breaks (text wrapping) within the source. pre
-
Sequences of white space are preserved. Lines are only broken at newline characters in the source and at
<br>
elements. pre-wrap
-
Sequences of white space are preserved. Lines are broken at newline characters, at
<br>
, and as necessary to fill line boxes. pre-line
-
Sequences of white space are collapsed. Lines are broken at newline characters, at
<br>
, and as necessary to fill line boxes. break-spaces
-
The behavior is identical to that of
pre-wrap
, except that:- Any sequence of preserved white space always takes up space, including at the end of the line.
- A line breaking opportunity exists after every preserved white space character, including between white space characters.
- Such preserved spaces take up space and do not hang, and thus affect the box’s intrinsic sizes (min-content size and max-content size).
The following table summarizes the behavior of the various white-space
values:
New lines | Spaces and tabs | Text wrapping | End-of-line spaces | End-of-line other space separators | |
---|---|---|---|---|---|
normal |
Collapse | Collapse | Wrap | Remove | Hang |
nowrap |
Collapse | Collapse | No wrap | Remove | Hang |
pre |
Preserve | Preserve | No wrap | Preserve | No wrap |
pre-wrap |
Preserve | Preserve | Wrap | Hang | Hang |
pre-line |
Preserve | Collapse | Wrap | Remove | Hang |
break-spaces |
Preserve | Preserve | Wrap | Wrap | Wrap |
Note: There is a distinction made between spaces and other space separators. These are defined as follows:
- spaces
-
Spaces (U+0020), tabs (U+0009), and segment breaks (such as newlines).
- other space separators
-
All other space separators defined in Unicode, other than those already defined as spaces.
Where white space is said to hang, this can affect the size of the box when measured for intrinsic sizing.
Collapsing of white space
The CSS Text specification contains a Collapsing and Transformation section that precisely defines what «white space is collapsed» means, including an example with an illustration. Usually, it means reducing sequences of multiple white-space characters down to a single space character — though in some cases it means reducing them to no character (the empty string).
Formal definition
Initial value | normal |
---|---|
Applies to | all elements |
Inherited | yes |
Computed value | as specified |
Animation type | discrete |
Formal syntax
white-space =
normal |
pre |
nowrap |
pre-wrap |
break-spaces |
pre-line
Examples
Basic example
code {
white-space: pre;
}
Line breaks inside <pre> elements
pre {
white-space: pre-wrap;
}
In action
HTML
<div id="css-code" class="box">
p { white-space:
<select>
<option>normal</option>
<option>nowrap</option>
<option>pre</option>
<option>pre-wrap</option>
<option>pre-line</option>
<option>break-spaces</option>
</select>
}
</div>
<div id="results" class="box">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
</div>
.box {
width: 300px;
padding: 16px;
border-radius: 10px;
}
#css-code {
background-color: rgb(220, 220, 220);
font-size: 16px;
font-family: monospace;
}
#css-code select {
font-family: inherit;
}
#results {
background-color: rgb(230, 230, 230);
overflow-x: scroll;
height: 400px;
white-space: normal;
font-size: 14px;
}
const select = document.querySelector("#css-code select");
const results = document.querySelector("#results p");
select.addEventListener("change", (e) => {
results.setAttribute("style", `white-space: ${e.target.value}`);
});
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt
in culpa qui officia deserunt mollit anim id est laborum.
</p>
Result
Specifications
Specification |
---|
CSS Text Module Level 3 # white-space-property |
Browser compatibility
BCD tables only load in the browser
See also
- Properties that define how words break within themselves:
overflow-wrap
,word-break
,hyphens
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
Example
Demonstrate different values of the white-space property:
p.a {
white-space: nowrap;
}
p.b {
white-space: normal;
}
p.c {
white-space:
pre;
}
Try it Yourself »
Definition and Usage
The white-space
property specifies how white-space inside an element is handled.
Show demo ❯
Default value: | normal |
---|---|
Inherited: | yes |
Animatable: | no. Read about animatable |
Version: | CSS1 |
JavaScript syntax: | object.style.whiteSpace=»nowrap» Try it |
Browser Support
The numbers in the table specify the first browser version that fully supports the property.
Property | |||||
---|---|---|---|---|---|
white-space | 1.0 | 8.0 | 3.5 | 3.0 | 9.5 |
CSS Syntax
white-space: normal|nowrap|pre|pre-line|pre-wrap|initial|inherit;
Property Values
Value | Description | Demo |
---|---|---|
normal | Sequences of whitespace will collapse into a single whitespace. Text will wrap when necessary. This is default | Demo ❯ |
nowrap | Sequences of whitespace will collapse into a single whitespace. Text will never wrap to the next line. The text continues on the same line until a <br> tag is encountered |
Demo ❯ |
pre | Whitespace is preserved by the browser. Text will only wrap on line breaks. Acts like the <pre> tag in HTML |
Demo ❯ |
pre-line | Sequences of whitespace will collapse into a single whitespace. Text will wrap when necessary, and on line breaks | Demo ❯ |
pre-wrap | Whitespace is preserved by the browser. Text will wrap when necessary, and on line breaks | Demo ❯ |
initial | Sets this property to its default value. Read about initial | |
inherit | Inherits this property from its parent element. Read about inherit |
Related Pages
CSS tutorial: CSS Text Spacing
HTML DOM reference: whiteSpace property
Internet Explorer | Chrome | Opera | Safari | Firefox | Android | iOS | ||||
6.0+ | 8.0+ | 1.0+ | 4.0+ | 9.5+ | 1.0+ | 3.0+ | 1.0+ | 3.5+ | 1.0+ | 1.0+ |
Краткая информация
Значение по умолчанию | normal |
---|---|
Наследуется | Да |
Применяется | К блочным элементам |
Ссылка на спецификацию | http://www.w3.org/TR/CSS21/text.html#propdef-white-space |
Версии CSS
CSS 1 | CSS 2 | CSS 2.1 | CSS 3 |
---|---|---|---|
Описание
Свойство white-space устанавливает, как отображать
пробелы между словами. В обычных условиях любое количество пробелов в коде HTML
показывается на веб-странице как один. Исключением является тег <pre>,
помещенный в этот контейнер текст выводится со всеми пробелами, как он был отформатирован
пользователем. Таким образом, white-space имитирует
работу тега <pre>, но в отличие от него не меняет шрифт
на моноширинный.
Синтаксис
white-space: normal | nowrap | pre | pre-line | pre-wrap | inherit
Значения
- normal
- Текст в окне браузера выводится как обычно, переносы строк устанавливаются
автоматически. - nowrap
- Пробелы не учитываются, переносы строк в коде HTML игнорируются, весь текст отображается одной строкой;
вместе с тем, добавление тега <br> переносит текст
на новую строку. - pre
- Текст показывается с учетом всех пробелов и переносов, как они были добавлены
разработчиком в коде HTML.
Если строка получается слишком длинной и не помещается в окне браузера, то будет добавлена горизонтальная полоса прокрутки. - pre-line
- В тексте пробелы не учитываются, текст автоматически переносится на следующую строку, если он не помещается в заданную область.
- pre-wrap
- В тексте сохраняются все пробелы и переносы, однако если строка по ширине не помещается в заданную область, то текст автоматически будет перенесен на следующую строку.
- inherit
- Наследует значение родителя.
Действие значений на текст представлено в табл. 1.
Значение | Перенос текста | Пробелы |
---|---|---|
normal | Переносится | Не учитываются |
nowrap | Не переносится | Не учитываются |
pre | Не переносится | Учитываются |
pre-line | Переносится | Не учитываются |
pre-wrap | Переносится | Учитываются |
Пример
HTML5CSS2.1IECrOpSaFx
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>white-space</title>
<style>
.example {
border: 1px dashed #634f36; /* Параметры рамки */
background: #fffff5; /* Цвет фона */
font-family: "Courier New", Courier, monospace; /* Семейство шрифта */
padding: 7px; /* Поля вокруг текста */
margin: 0 0 1em; /* Отступы */
white-space: pre; /* Учитываются все пробелы и переносы */
}
.exampleTitle {
border: 1px solid black; /* Параметры рамки */
border-bottom: none; /* Убираем линию снизу */
padding: 3px; /* Поля вокруг текста */
display: inline; /* Отображать как встроенный элемент */
background: #efecdf; /* Цвет фона */
font-weight: bold; /* Жирное начертание */
font-size: 90%; /* Размер шрифта */
margin: 0; /* Убираем отступы */
white-space: nowrap; /* Переносов в тексте нет */
}
</style>
</head>
<body>
<p class="exampleTitle">Пример</p>
<p class="example">
<html>
<body>
<b>Великая теорема Ферма</b><br>
<i>X <sup><small>n</small></sup>
+ Y <sup><small>n</small></sup> =
Z <sup><small>n</small></sup></i><br>
где n - целое число > 2
</body>
</html>
</p>
</body>
</html>
Результат данного примера показан на рис. 1.
Рис. 1. Применение свойства white-space
Объектная модель
[window.]document.getElementById(«elementID«).style.whiteSpace
Браузеры
Браузер Internet Explorer до версии 7.0 включительно не поддерживает значения pre-line, pre-wrap и inherit. Для <textarea> значения normal и pre ведут себя как pre-wrap, а значение nowrap ведет себя как pre-line.
Opera до версии 9.5 не поддерживает значение pre-line. Для <textarea> значения normal и pre ведут себя как pre-wrap, а значение nowrap ведет себя как pre-line.
Safari до версии 3.0 и iOS не поддерживают значения pre-wrap и pre-line.
Firefox до версии 2.0 включительно не поддерживает значения pre-line и pre-wrap. Для <textarea> значения normal, nowrap, и pre воспринимаются как pre-wrap.
I feel silly for not being able to figure this out, but how do I turn off wordwrap? the css word-wrap
property can be forced on with break-word
, but cannot be forced off (only can be left alone with normal
value).
How do I force word wrap off?
Jon
425k79 gold badges733 silver badges803 bronze badges
asked Jan 10, 2011 at 23:19
Alexander BirdAlexander Bird
38k42 gold badges124 silver badges159 bronze badges
2
You need to use the CSS white-space
attribute.
In particular, white-space: nowrap
and white-space: pre
are the most commonly used values. The first one seems to be what you ‘re after.
answered Jan 10, 2011 at 23:21
0
Added webkit specific values missing from above
white-space: -moz-pre-wrap; /* Firefox */
white-space: -o-pre-wrap; /* Opera */
white-space: pre-wrap; /* Chrome */
word-wrap: break-word; /* IE */
answered Jul 7, 2015 at 15:07
I wonder why you find as solution the «white-space» with «nowrap» or «pre», it is not doing the correct behaviour: you force your text in a single line!
The text should break lines, but not break words as default. This is caused by some css attributes: word-wrap, overflow-wrap, word-break, and hyphens. So you can have either:
word-break: break-all;
word-wrap: break-word;
overflow-wrap: break-word;
-webkit-hyphens: auto;
-moz-hyphens: auto;
-ms-hyphens: auto;
hyphens: auto;
So the solution is remove them, or override them with «unset» or «normal»:
word-break: unset;
word-wrap: unset;
overflow-wrap: unset;
-webkit-hyphens: unset;
-moz-hyphens: unset;
-ms-hyphens: unset;
hyphens: unset;
UPDATE: i provide also proof with JSfiddle: https://jsfiddle.net/azozp8rr/
answered May 12, 2018 at 9:55
zodzod
3773 silver badges4 bronze badges
2
white-space: nowrap;
: Will never break text, will keep other defaults
white-space: pre;
: Will never break text, will keep multiple spaces after one another as multiple spaces, will break if explicitly written to break(pressing enter in html etc)
answered Nov 13, 2020 at 20:28
1
This worked for me to stop silly work breaks from happening within Chrome textareas
word-break: keep-all;
answered Oct 2, 2019 at 21:54
If you want a HTML only solution, we can just use the pre
tag. It defines «preformatted text» which means that it does not format word-wrapping. Here is a quick example to explain:
div {
width: 200px;
height: 200px;
padding: 20px;
background: #adf;
}
pre {
width: 200px;
height: 200px;
padding: 20px;
font: inherit;
background: #fda;
}
<div>Look at this, this text is very neat, isn't it? But it's not quite what we want, though, is it? This text shouldn't be here! It should be all the way over there! What can we do?</div>
<pre>The pre tag has come to the rescue! Yay! However, we apologise in advance for any horizontal scrollbars that may be caused. If you need support, please raise a support ticket.</pre>
answered Nov 4, 2020 at 19:41
corn on the cobcorn on the cob
1,8043 gold badges19 silver badges26 bronze badges