The word-spacing CSS property sets the length of space between words and between tags.
Try it
Syntax
/* Keyword value */
word-spacing: normal;
/* <length> values */
word-spacing: 3px;
word-spacing: 0.3em;
/* Global values */
word-spacing: inherit;
word-spacing: initial;
word-spacing: revert;
word-spacing: revert-layer;
word-spacing: unset;
Values
normal-
The normal inter-word spacing, as defined by the current font and/or the browser.
<length>-
Specifies extra spacing in addition to the intrinsic inter-word spacing defined by the font.
Examples
HTML
<div id="mozdiv1">Lorem ipsum dolor sit amet.</div>
<div id="mozdiv2">Lorem ipsum dolor sit amet.</div>
CSS
#mozdiv1 {
word-spacing: 15px;
}
#mozdiv2 {
word-spacing: 5em;
}
Accessibility concerns
A large positive or negative word-spacing value will make the sentences the styling is applied to unreadable. For text styled with a very large positive value, the words will be so far apart that it will no longer appear to be a sentence. For text styled with a large negative value, the words will overlap each other to the point where the beginning and end of each word is unrecognizable.
Legible word-spacing must be determined on a case-by-case basis, as different font families have different character widths. There is no one value that can ensure all font families automatically maintain their legibility.
- MDN Understanding WCAG, Guideline 1.4 explanations
- Understanding Success Criterion 1.4.8 | W3C Understanding WCAG 2.0
Formal definition
| Initial value | normal |
|---|---|
| Applies to | all elements. It also applies to ::first-letter and ::first-line. |
| Inherited | yes |
| Percentages | refer to the width of the affected glyph |
| Computed value | absolute <length> |
| Animation type | a length |
Formal syntax
word-spacing =
normal |
<length>
Specifications
| Specification |
|---|
| CSS Text Module Level 3 # word-spacing-property |
Browser compatibility
BCD tables only load in the browser
See also
Устанавливает интервал между словами. Если для текста задано выравнивание через text-align со значением justify (выравнивание по ширине), то интервал между словами будет установлен принудительно, но не меньше значения, указанного через word-spacing.
Краткая информация
| Значение по умолчанию | normal |
|---|---|
| Наследуется | Да |
| Применяется | Ко всем элементам |
| Анимируется | Да |
Синтаксис
word-spacing: <размер> | normal
Синтаксис
| Описание | Пример | |
|---|---|---|
| <тип> | Указывает тип значения. | <размер> |
| A && B | Значения должны выводиться в указанном порядке. | <размер> && <цвет> |
| A | B | Указывает, что надо выбрать только одно значение из предложенных (A или B). | normal | small-caps |
| A || B | Каждое значение может использоваться самостоятельно или совместно с другими в произвольном порядке. | width || count |
| [ ] | Группирует значения. | [ crop || cross ] |
| * | Повторять ноль или больше раз. | [,<время>]* |
| + | Повторять один или больше раз. | <число>+ |
| ? | Указанный тип, слово или группа не является обязательным. | inset? |
| {A, B} | Повторять не менее A, но не более B раз. | <радиус>{1,4} |
| # | Повторять один или больше раз через запятую. | <время># |
Значения
В качестве значений принимаются любые единицы длины, принятые в CSS — например, пиксели (px), дюймы (in), пункты (pt) и др. Допустимо использовать отрицательное значение, но читаемость текста может при этом снизиться. Процентная запись запрещена.
- normal
- Устанавливает интервал между словами как обычно.
Песочница
Винни-Пух был всегда не прочь немного подкрепиться, в особенности часов в одиннадцать утра, потому что в это время завтрак уже давно окончился, а обед ещё и не думал начинаться. И, конечно, он страшно обрадовался, увидев, что Кролик достаёт чашки и тарелки.
div {
word-spacing: {{ playgroundValue }}px;
}
Пример
<!DOCTYPE html>
<html>
<head>
<meta charset=»utf-8″>
<title>word-spacing</title>
<style>
.tel {
word-spacing: 10px;
font-size: 2em;
}
</style>
</head>
<body>
<p class=»tel»>Тел.: 555-221-061</p>
</body>
</html>
В данном примере задаётся фиксированное расстояние между номером телефона и текстом (рис. 1).
Рис. 1. Применение свойства word-spacing
Объектная модель
Объект.style.wordSpacing
Спецификация
| Спецификация | Статус |
|---|---|
| CSS Text Level 3 | Рабочий проект |
| CSS Transitions | Рабочий проект |
| CSS Level 2 (Revision 1) | Рекомендация |
| CSS Level 1 | Рекомендация |
Спецификация
Каждая спецификация проходит несколько стадий одобрения.
- Recommendation (Рекомендация) — спецификация одобрена W3C и рекомендована как стандарт.
- Candidate Recommendation (Возможная рекомендация) — группа, отвечающая за стандарт, удовлетворена, как он соответствует своим целям, но требуется помощь сообщества разработчиков по реализации стандарта.
- Proposed Recommendation (Предлагаемая рекомендация) — на этом этапе документ представлен на рассмотрение Консультативного совета W3C для окончательного утверждения.
- Working Draft (Рабочий проект) — более зрелая версия черновика после обсуждения и внесения поправок для рассмотрения сообществом.
- Editor’s draft (Редакторский черновик) — черновая версия стандарта после внесения правок редакторами проекта.
- Draft (Черновик спецификации) — первая черновая версия стандарта.
Браузеры
| 6 | 12 | 1 | 3.5 | 1 | 1 |
Браузеры
В таблице браузеров применяются следующие обозначения.
- — элемент полностью поддерживается браузером;
- — элемент браузером не воспринимается и игнорируется;
- — при работе возможно появление различных ошибок, либо элемент поддерживается с оговорками.
Число указывает версию браузреа, начиная с которой элемент поддерживается.
-
normal - 0
-
initial - normal
-
inherit - наследует значение родителя
-
unset - наследует значение родителя
Свойство word-spacing наследуется, применяется ко всем элементам, применяется ко всем элементам, изменяет текст и строчные элементы
<style>
div {
word-spacing: normal;
}
</style>
<div>Свойство <code>word-spacing</code> наследуется, применяется ко всем элементам, изменяет текст и строчные элементы</div>
Что такое word-spacing CSS
Между словами используется символ пробела. Положительное значение свойства word-spacing задаёт к пробелу дополнительное расстояние, тем самым увеличивая отступ между словами. Отрицательное значение, наоборот, уменьшает.
Значение word-spacing в процентах устанавливает дополнительное расстояние между словами в процентах от длины символа пробела.
Отступы между inline или inline-block элементами
Если два и более пробела идут подряд и не являются неразрывными, то они показываются как один. Знак переноса на новую строку также является пробельным символом. Например, «слово в слово
про
слово» в исходном коде выглядит так:
«слово в слово
про
слово»
Изменить это поведение можно с помощью свойства white-space. У тега <pre> по умолчанию white-space имеет значение pre и моноширинный шрифт.
Отступ/выступ первой строки в абзаце можно установить с помощью свойства text-indent.
Те же правила и свойства CSS распространяются и на inline и inline-block элементы [подробнее]. Например, «слово в слово
про
слово».
<style>
span {
display: inline-block;
padding: .5em;
border: 1px solid green;
background-color: #fff5d7;
}
</style>
«<span>слово</span> <span>в</span> <span>слово</span>
<span>про</span>
<span>слово</span>»
Как убрать расстояние между inline-block элементами
<style>
li {
display: inline-block;
padding: .5em;
border: 1px solid green;
background-color: #fff5d7;
}
</style>
<ol>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ol>
Вариант 1. Удалить символ пробела
<style>
li {
display: inline-block;
padding: .5em;
border: 1px solid green;
background-color: #fff5d7;
}
</style>
<ol>
<li></li><li></li><li></li><li></li><li></li>
</ol>
В HTML5 для некоторых элементов закрывающийся тег может быть опущен. [whatwg.org] Предполагается, что он присутствует перед следующим указанным в спецификации тегом (скажем, </li> прижат без промежутка к следующему <li> или к закрывающемуся тегу родительского элемента).
<style>
li {
display: inline-block;
padding: .5em;
border: 1px solid green;
background-color: #fff5d7;
}
</style>
<ol>
<li>
<li>
<li>
<li>
<li>
</ol>
Вариант 2. Задать отрицательное значение word-spacing родительскому элементу
<style>
ol {
word-spacing: -100%;
}
li {
display: inline-block;
padding: .5em;
border: 1px solid green;
word-spacing: normal;
background-color: #fff5d7;
}
</style>
<ol>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ol>
Как настроить интервал между inline-block элементами
Если строка начинается с пробела, то он игнорируется. При уменьшении ширины родителя, смещённый вниз inline-блок вплотную прижимается к границе предка. Что более предпочтительно, чем поведение margin.
- 1
- 2
- 3
- 4
- 5
- 1
- 2
- 3
- 4
- 5
<style>
ol {
border: 1px solid blue;
padding: 0;
overflow: auto;
resize: horizontal;
}
ol li {
display: inline-block;
margin: 0;
border: 1px solid green;
padding: .5em;
vertical-align: middle;
background-color: #fff5d7;
}
ol:nth-of-type(1) {
word-spacing: 4em;
}
ol:nth-of-type(1) li {
word-spacing: normal;
}
ol:nth-of-type(2) li + li {
margin-left: 4em;
}
</style>
<ol>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ol>
<ol>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ol>
Можно также взглянуть на похожий пример с выравниванием блоков по центру.
Свойство word-spacing устанавливает интервал между словами.
Если для текста задано выравнивание через text-align со значением justify (выравнивание по ширине), то интервал между словами будет установлен принудительно, но не меньше значения, указанного через word-spacing.
Демо¶
Текст
- hanging-punctuation
- hyphens
- letter-spacing
- line-break
- overflow-wrap
- paint-order
- tab-size
- text-align
- text-align-last
- text-indent
- text-justify
- text-size-adjust
- text-transform
- white-space
- word-break
- word-spacing
- letter-spacing
- text-decoration
- text-decoration-color
- text-decoration-line
- text-decoration-style
- text-decoration-thickness
- text-decoration-skip
- text-decoration-skip-ink
- text-emphasis
- text-emphasis-color
- text-emphasis-position
- text-emphasis-style
- text-indent
- text-rendering
- text-shadow
- text-underline-position
- text-transform
- white-space
- word-spacing
Синтаксис¶
/* Keyword value */
word-spacing: normal;
/* <length> values */
word-spacing: 3px;
word-spacing: 0.3em;
/* <percentage> values */
word-spacing: 50%;
word-spacing: 200%;
/* Global values */
word-spacing: inherit;
word-spacing: initial;
word-spacing: unset;
Значения¶
В качестве значений принимаются любые единицы длины, принятые в CSS — например, пикселы (px), дюймы (in), пункты (pt) и др. Значение может быть и отрицательным, но следует проверять работоспособность в разных браузерах. Процентная запись не применима.
normal- Устанавливает интервал между словами как обычно.
Значение по-умолчанию: normal
Применяется ко всем элементам
Спецификации¶
- CSS Text Level 3
- CSS Level 2 (Revision 1)
- CSS Level 1
Описание и примеры¶
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>word-spacing</title>
<style>
.tel {
word-spacing: 10px;
font-size: 2em;
}
</style>
</head>
<body>
<p class="tel">Тел.: 555-221-061</p>
</body>
</html>
Text spacing and placement in CSS is controlled using the letter-spacing, word-spacing, line-height, and text-indent properties. Learn how to set text spacing and placement in the following steps.
- The
letter-spacingproperty is used to specify the amount of space between letters. The amount indicated is in addition to the default spacing. The amount is specified in units. For example:<div style="letter-spacing: 1em;">It's a wide wide word!</div> - The
word-spacingproperty is used to specify the amount of space between words. The amount indicated is in addition to the default spacing. The amount is specified in units. For example:<div style="word-spacing: 1em;">It's a wide wide sentence!</div> - The
line-heightproperty is used to specify the amount of vertical space between lines of text. The line-height can be specified in number of units, percentage, or with a multiplier.<div style="line-height: 1.5;"> - The
text-indentproperty is used to indent (or outdent) the first line of a block of text. The value can be specified in number of units or in percentage of the width of the containing block.<div style="text-indent: 50px;">
The following code sample shows all of these properties in use:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Spacing and Line Height</title>
</head>
<body>
<div style="margin-left: 300px;">
<h1>Spacing and Line Height</h1>
<h2>Letter Spacing</h2>
<div style="letter-spacing: 1em;">letter-spacing: 1em</div>
<div style="letter-spacing: -1em;">letter-spacing: -1em</div>
<h2>Word Spacing</h2>
<div style="word-spacing: 1em;">word-spacing: 1em</div>
<div style="word-spacing: 1em;">It's a wide wide sentence.</div>
<h2>Line Height</h2>
<div style="line-height: 1.5;">
line-height: 1.5<br>
line-height: 1.5<br>
line-height: 1.5
</div>
<div style="line-height: 150%;">
line-height: 150%<br>
line-height: 150%<br>
line-height: 150%
</div>
<div style="line-height: 1.5em;">
line-height: 1.5em<br>
line-height: 1.5em<br>
line-height: 1.5em
</div>
<h2>Text-Indent</h2>
<div style="text-indent: 50px;">
text-indent:50px - text-indent only applies to the first line of text.<br>
The next lines will not be indented.
</div>
<div style="text-indent: 10%;">
text-indent:10% - text-indent only applies to the first line of text.<br>
The next lines will not be indented.
</div>
</div>
</body>
</html>
The above code will render the following:


