- white-space
- Try it
- Syntax
- Values
- Collapsing of white space
- Formal definition
- Formal syntax
- Examples
- Basic example
- Line breaks inside elements
- In action
- Specifications
- Browser compatibility
- See also
- Пробел html — как вставить на страницу
- Таблица с кодами html пробелов
- Пробел в HTML
- Неразрывный пробел HTML
- Тонкий пробел
- Другие типы пробелов в языке HTML
- Пробел при помощи CSS
- HTML Space – How to Add a Non-breaking Space with the Character Entity
- First, What Are Character Entities?
- How to Add Non-breaking Spaces in HTML with
- What if you want a bunch of spaces in your code?
- Why would you need a non-breaking space in your code?
- Conclusion
white-space
The white-space CSS property sets how white space inside an element is handled.
Try it
The property specifies two things:
Note: To make words break within themselves, use overflow-wrap , word-break , or hyphens instead.
Syntax
/* Single keyword values */ white-space: normal; white-space: nowrap; white-space: pre; white-space: pre-wrap; white-space: pre-line; white-space: break-spaces; /* white-space-collapse and text-wrap shorthand values */ white-space: collapse balance; white-space: preserve nowrap; /* Global values */ white-space: inherit; white-space: initial; white-space: revert; white-space: revert-layer; white-space: unset;
Values
white-space property values can be specified as a single keyword chosen from the list of values below, or two values representing shorthand for the white-space-collapse and text-wrap properties.
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.
Collapses white space as for normal , but suppresses line breaks (text wrapping) within the source.
Sequences of white space are preserved. Lines are only broken at newline characters in the source and at elements.
Sequences of white space are preserved. Lines are broken at newline characters, at , and as necessary to fill line boxes.
Sequences of white space are collapsed. Lines are broken at newline characters, at , and as necessary to fill line boxes.
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, thus affecting the box’s intrinsic sizes ( min-content size and max-content size).
The following table summarizes the behavior of the various white-space keyword 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 (U+0020), tabs (U+0009), and segment breaks (such as newlines).
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
Formal definition
Formal syntax
white-space =
normal |
pre |
nowrap |
pre-wrap |
break-spaces |
pre-line
Examples
Basic example
Line breaks inside elements
In action
div id="css-code" class="box"> p < white-space: select> option>normaloption> option>nowrapoption> option>preoption> option>pre-wrapoption> option>pre-lineoption> option>break-spacesoption> option>preserve nowrapoption> 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; > #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; 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>`); >);
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Пробел html — как вставить на страницу
Чтобы пробел html отобразился «как пробел», его необходимо вставлять в виде специального кода, иначе множественные пробелы просто склеятся.
Ниже представлена таблица с кодами для вставки пробелов.
Таблица с кодами html пробелов
\u0020 | межсловный, его печатает кнопка Space | |
| \u00A0 | межсловный, неразрывный |
\u2009 | тонкий | |
\u202f | тонкий, неразрывный | |
  | \u200A | волосяной (очень короткий пробел) |
| \u200B | без ширины, при необходимости переносит слово |
| \u00AD | без ширины, при необходимости переносит слово, добавляя к нему дефис |
⁠ | \u2060 | без ширины, неразрывный |
равен двум стандартным пробелам | ||
\u2003 | равен четырем стандартным пробелам | |
  | \u2007 | равен ширине цифры, если все цифры одинаковой ширины, неразрывный |
  | \u2008 | равен ширине запятой |
␣ | \u2423 | обозначение символа |
Отличительной особенностью неразрывного пробела являются то, что при переносе слова он как бы цепляется к предыдущему слову и может переноситься на новую строку только целиком.
Подводя итоги, я рекомендую пользоваться тремя вариантами кодами html-пробелов:
— неразрывный пробел — двойной пробел — четырех кратный пробел
Пробел в HTML
Бывают случаи, когда не хочется менять стили ради какого-то одного элемента, или необходимо вставить несколько пробелов в тексте из соображений эстетики или стилистики форматирования текста. И тут встает вопрос: «Как сделать пробел в HTML, чтобы текст красиво отображался, и при этом избежать избыточности кода?» Для этого рассмотрим виды пробелов и примеры их использования в HTML-коде.
Неразрывный пробел HTML
В случаях, когда нужно не отрывать части текста друг от друга, поможет неразрывный пробел, код которого выглядит следующим образом:
Это так называемый, «non breaking space».
Примеры использования неразрывного пробела:
Тонкий пробел
Код пробела HTML, который мы рассмотрели выше, является повсеместным. Но бывают случаи, когда обычный пробел оказывается слишком «большим». Тогда на смену ему приходит тонкий пробел. Это пробел, ширина которого составляет четверть кегля используемого шрифта. Обозначается тонкий пробел следующим образом:
и используется, по большей части, для разбиения разрядов чисел, например, «15 000 000 долларов» стоит записать так:
Примечание: Тонкий пробел может некорректно отображаться в старых версиях некоторых из браузеров, но во всех последних версиях работает на «ура».
Другие типы пробелов в языке HTML
Помимо наиболее актуальных видов, что мы рассмотрели выше, существуют и другие.
- — пробел длины буквы N;
- — пробел длины буквы M;
- — несоединяющий символ нулевой длины;
- — соединяющий символ нулевой длины.
Примечание: Если вам нужно поставить несколько пробелов подряд, обрамите текст тегом :
Конструктор сайтов «Нубекс»Пробел при помощи CSS
Вариант создания табуляции (отступа) с помощью CSS можно решить с помощью следующего приёма:
Конструктор сайтов «Нубекс»
HTML Space – How to Add a Non-breaking Space with the Character Entity
Kolade Chris
In HTML, you can’t create an extra blank space after the space ( ) character with the spacebar. If you want 10 blank spaces in your HTML code and you try to add them with the spacebar, you’ll only see one space in the browser.
Also, one or more of the words that are supposed to be together might break into a new line.
So, in this article, I will show you how to create any number of blank spaces you want in your code, and how to add a non-breaking space with the character entity.
First, What Are Character Entities?
Character entities are reserved for displaying various characters in the browser.
For instance, the less than symbol ( < ) and greater than symbol ( >) are reserved for tags in HTML. If you want to use them in your code, HTML might mistake them for opening and closing tags.
If you want to use them as «greater than» and «less than», you need to use their respective character entities ( < and > ). Then you can safely display them in the browser.
How to Add Non-breaking Spaces in HTML with
Since the browser will display only one blank space even if you put millions in your code, HTML has the character entity. It makes it possible to display multiple blank spaces.
Without the character entity, this is how your code would look:
Lemurs are primates found exclusively in the isolated island of Madagascar. Lemurs are primates just like apes and monkeys, but they evolved independently and are unique. The numbers of lemurs are dwindling due to poaching and other destructive human activities. Lemurs are worth more than $2 Trillion. In fact, no amount of money can ever buy one. So, protect lemurs!
I have added some CSS to make the HTML clearer and to make it easier to see what I’m trying to show:
In the HTML code below, I inserted some character entities to create multiple blank spaces:
Lemurs are primates found exclusively in the isolated island of Madagascar. Lemurs are primates just like apes and monkeys, but they evolved independently and are unique. The numbers of lemurs are dwindling due to poaching and other destructive human activities. Lemurs are worth more than $2 Trillion. In fact, no amount of money can ever buy one. So, protect lemurs!
You can see there are 5 blank spaces between the first two words, and 4 between the antepenultimate and penultimate words. That’s because I inserted 5 and 4 characters, respectively.
Without the character entity, that wouldn’t be possible.
What if you want a bunch of spaces in your code?
What if, for instance, you want 10 blank spaces in your code? Writing 10 times would be redundant and boring.
Instead, HTML provides the character entity for 2 non-breaking spaces, and for 4 non-breaking spaces.
Lemurs are primates found exclusively in the isolated island of Madagascar. Lemurs are primates just like apes and monkeys, but they evolved independently and are unique. The numbers of lemurs are dwindling due to poaching and other destructive human activities. Lemurs are worth more than $2 Trillion. In fact, no amount of money can ever buy one. So, protect lemurs!
In the code above, I inserted 5 blank spaces between the first two words by using once (4 spaces) and once (1 space). Then I used 2 &ensp entities between the antepenultimate and penultimate words. So, the number of blank spaces remain the same as in the first example:
Why would you need a non-breaking space in your code?
Sometimes, HTML might break up words that are supposed to be together into another line – for example, initials, units, dates, amount of money, and more.
The character entity prevents this from happening. When you insert the character between such words, it will render a space and will never let any of the words break into a new line.
In the HTML code below, I have some information about lemurs – the beautiful primates found in Madagascar:
Lemurs are primates found exclusively in the isolated island of Madagascar. Lemurs are primates just like apes and monkeys, but they evolved independently and are unique. Th numbers of lemurs are dwindling due to poaching and other destructive human activities. Lemurs are worth more than $2 Trillion. In fact, no amount of money can ever buy one. So, protect lemurs!
I have some CSS to make it clearer and show what I’m trying to show:
The result looks like this:
You can see that the $2 Trillion breaks, which does not look good as it might confuse the reader.
The character entity forces the two words together:
Lemurs are primates found exclusively in the isolated island of Madagascar. Lemurs are primates just like apes and monkeys, but they evolved independently and are unique. Th numbers of lemurs are dwindling due to poaching and other destructive human activities. Lemurs are worth more than $2 Trillion. In fact, no amount of money can ever buy one. So, protect lemurs!
Conclusion
You have seen that with the , , and the character entities, you can display blank spaces in the browser. This isn’t possible just using the spacebar key.
You can also use the character entity in specific places to prevent words that should stay together from breaking into the next line.
Thank you for reading, and keep coding.