CSS-свойство word-spacing
устанавливает длину пробела между словами и между тегами.
Интерактивный пример
Синтаксис
/* Значение ключевым словом */
word-spacing: normal;
/* <length> значения */
word-spacing: 3px;
word-spacing: 0.3em;
/* <percentage> значения */
word-spacing: 50%;
word-spacing: 200%;
/* Глобальные значения */
word-spacing: inherit;
word-spacing: initial;
word-spacing: unset;
Значения
normal
-
Нормальный интервал между словами, определённый текущим шрифтом и/или браузером.
length
-
Определяет дополнительный интервал в дополнение к внутреннему интервалу между словами, определяемому шрифтом.
percentage
-
Определяет дополнительный интервал как процент от предварительной ширины символа.
Формальный синтаксис
word-spacing =
normal | (en-US)
<length>
Пример
HTML
<div id="mozdiv1">Here are many words...</div>
<div id="mozdiv2">...and many more!</div>
CSS
#mozdiv1 {
word-spacing: 15px;
}
#mozdiv2 {
word-spacing: 5em;
}
Проблемы доступности
Большое положительное или отрицательное значение word-spacing
может сделать предложения, к которым применяется стиль, нечитаемыми. Для текста, стилизованного с очень большими положительными значениями, слова будут так далеки друг от друга, что он больше не будет казаться предложением. Для текста, стилизованного с очень большими отрицательными значениями, слова будут перекрывать друг от друга до точки, где начало и конец каждого слова будут неразличимы.
Разборчивый word-spacing
должен быть определён в каждом конкретном случае, так как различные семейства шрифтов имеют различную ширину символов. Нет ни одного значения, которое может обеспечить для всех семейств шрифтов автоматическое сохранение разборчивости.
- MDN Understanding WCAG, Guideline 1.4 explanations
- Understanding Success Criterion 1.4.8 | W3C Understanding WCAG 2.0
Спецификации
Specification |
---|
CSS Text Module Level 3 # word-spacing-property |
Начальное значение | normal |
---|---|
Применяется к | все элементы. Это также применяется к ::first-letter и ::first-line . |
Наследуется | да |
Проценты | зависит от ширины символа |
Обработка значения | абсолютная length |
Animation type | длина |
Поддержка браузерами
BCD tables only load in the browser
Демонстрация возможностей CSS для настройки расстояний между буквами, строками, табуляции и других свойств шрифтов.
1
Красная строка
Свойство text-indent
устанавливает сдвиг первой строки, цвет первой буквы можно определить свойством :first-letter.
p {
text-indent: 0px;
}
CSS
2
Расстояние между буквами
Свойство letter-spacing
устанавливает интервал между символами. В качестве значений принимаются единицы длины (px, in, pt, em, ex), допустимо отрицательное значение. Лучшая точность получается при использовании em.
p {
letter-spacing: 0em;
}
CSS
3
Ширина пробелов
Word-spacing
задает интервал между словами, значение можно указать в px, in, pt, em, ex.
p {
word-spacing: 0em;
}
CSS
4
Ширина табуляции
Свойство tab-size
устанавливает ширину табуляции в <textarea>
, <code>
, <pre>
и других элементах со свойством white-space: pre
. В качестве значения используется количество символов (по умолчанию или единицы длины.
Свойство пока ещё не стандартизировано W3C, но поддерживается современными браузерами.
pre {
-o-tab-size: 8;
-moz-tab-size: 8;
tab-size: 8;
}
CSS
5
Ширина букв
Свойство font-stretch
задаёт ширину символов в шрифте, работает только со шрифтами, у которых есть поддержка разных начертаний. Значения задаются константами или процентами:
normal |
100% |
Обычная ширина |
semi-condensed |
87.5% |
Узковатая ширина |
condensed |
75% |
Узкая ширина |
extra-condensed |
62.5% |
Очень узкая ширина |
ultra-condensed |
50% |
Самая узкая ширина |
semi-expanded |
112.5% |
Широковатая ширина |
expanded |
125% |
Средне-большая ширина |
extra-expanded |
150% |
Очень большая ширина |
ultra-expanded |
200% |
Самая большая ширина |
p {
font-stretch: 100%;
}
CSS
Второй прием увеличить ширину букв – растянуть элемент свойством transform scale от нулевой точки трансформации (transform-origin).
p {
transform-origin: 0 0;
transform: scale(1, 1);
}
CSS
Меняя второй параметр можно изменить высоту букв:
p {
transform-origin: 0 0;
transform: scale(1, 1);
}
CSS
6
Межстрочный интервал
Line-height
устанавливает интерлиньяж текста, отсчет ведется от базовой линии шрифта. Значение воспринимается как множитель от текущего размера шрифта, также отступ можно указать в em или px, отрицательное значение не допускается.
p {
line-height: 20px;
}
CSS
01.05.2020, обновлено 14.10.2020
Другие публикации
Если добавить атрибут contenteditable к элементу, его содержимое становится доступно для редактирования пользователю, а…
К сожалению разработчики прекратили поддержку и разработку проекта, но PHPExcel все равно остается популярной…
Список из 256 символов и их коды в ASCII.
Очень часто разработчики забывают про печатную версию сайта, поэтому можно встретить такой результат на бумаге…
С помощью расширения dompdf можно легко сформировать PDF файл. По сути, dompdf — это конвертер HTML в PDF который…
Градиент в цвет шрифта можно добавить с помощью CSS свойства background-clip: text, которое окрашивает текст в цвет или изображение указанного в background-image.
Download Article
Download Article
Adding extra space between words and paragraphs in HTML is very different than in apps like Microsoft Word. But don’t tear out your hair just yet—we’ll show you the easiest ways to control spacing between words and lines of text, as well as how to add extra space to the beginning of each paragraph so they are properly indented on the page. This wikiHow article teaches you different ways you can add spaces to your HTML code.
-
1
Open your HTML code in a text editor. You can use any text editor, such as Notepad for Windows, or TextEdit for macOS, to edit your code. If you press the spacebar multiple times to add extra space between words or characters, you won’t see those extra spaces on your webpage—HTML automatically converts multiple spaces into a single space. You can fix this by using non-breaking space characters instead of pressing the spacebar.
-
2
Type where you want to insert an extra space. Add one non-breaking space character for every space you want to add. Unlike pressing the spacebar multiple times in your HTML code, typing more than once creates as many spaces as there are instances of .[1]
- For example, let’s say you want three spaces between the words «What will you learn» and «today?» Instead of pressing the spacebar three times, just type between the two segments. Here’s an example:
<!DOCTYPE html> <html> <head> <title>wikiHow: How-to instructions you can trust.</title> </head> <body> <p>What will you learn&nbsp;&nbsp;&nbsp;today?</p> </body> </html>
Basically, just translates to «one space» in HTML.
Advertisement
- For example, let’s say you want three spaces between the words «What will you learn» and «today?» Instead of pressing the spacebar three times, just type between the two segments. Here’s an example:
-
3
Use other spacing characters as shortcuts. If you want to insert two spaces, four spaces, or indent the beginning of a line, you don’t have to type multiple times:
- Two spaces: Type  
- Four spaces: Type  
Advertisement
-
1
Open your HTML code. Another way to add more spaces to your code is to use the HTML <pre> tag. This tag essentially displays the text exactly as you type or paste it, spaces and all. Start by opening your code in a text editor like Notepad for Windows or TextEdit for macOS.
-
2
Type <pre> </pre> tags in the body of your document. Any text you want to keep preformatted with a particular amount of spaces and/or line breaks will go between these tags:
<!DOCTYPE html> <html> <head> <title>wikiHow: How-to instructions you can trust.</title> </head> <body> <pre> </pre> </body> </html>
-
3
Type or paste text exactly as intended between the «<pre>» and »<pre>» tags. In this example, we’re creating three spaces between words, as well as a line break. When pre-formatting text, any spaces between words, as well as line breaks you create by pressing «Enter» or «Return,» will be displayed on the webpage.[2]
<!DOCTYPE html> <html> <head> <title>wikiHow: How-to instructions you can trust.</title> </head> <body> <pre>What will you learn today?</pre> </body> </html>
Advertisement
-
1
Open your HTML code in a text editor. Do you want to add extra space between paragraphs or other elements on the page? Pressing Enter or Return a bunch of times in your code won’t do the trick, but adding a line break tag <br> will! Start by opening the HTML code of the page you want to edit.
-
2
Type <br> on each line you want to make blank. For example, if you want to insert just one extra blank horizontal line between two paragraphs, you’d just type one <br> once. But if you wanted to add three line breaks, you could type it three times: <br><br><br>.
- In this example, we’re adding two lines of extra space between our sentences:
<!DOCTYPE html> <html> <head> <title>wikiHow: How-to instructions you can trust.</title> </head> <body> <pre>What will you learn today?</pre> <br><br> <p>You will learn a lot!</p> </body> </html>
- In this example, we’re adding two lines of extra space between our sentences:
Advertisement
-
1
Open an HTML document. Let’s say you want to indent the beginning a paragraph with some space—let’s say 10 pixels. The best way to do this would be to use CSS (Cascading Style Sheets). We’ll cover two ways to do this—one lets you indent each paragraph manually, and another indents all paragraphs at once. Start by opening up your HTML document in a text editor.
-
2
Indent a single paragraph. If we want to indent the paragraph in our example, we can do so by adding the text-indent property to its <p> tag. In this example, we’ll be indenting our paragraph by 10px:
<!DOCTYPE html> <html> <head> <title>wikiHow: How-to instructions you can trust.</title> </head> <body> <p style="text-indent:10px">Welcome to wikiHow, the most trusted how-to site on the internet. wikiHow is where trusted research and expert knowledge come together.</p> <p> Since 2005, wikiHow has helped billions of people learn how to solve problems large and small. We work with credentialed experts, a team of trained researchers, and a devoted community to create the most reliable, comprehensive and delightful how-to content on the Internet.</p> </body> </html>
- Since we added the text-indent property to just the first paragraph, that is the only paragraph that will be indented. Read on to learn how to indent all paragraphs on the page the same way instead of just one!
-
3
Create a style section for your CSS. If we want to indent all paragraphs on our page, we can do so by defining the paragraph style in CSS. The style section goes into the head of your HTML code, or on a separate style sheet. Let’s add ours to the head, which is between the <head> and </head> tags:
<!DOCTYPE html> <html> <head> <title>wikiHow: How-to instructions you can trust.</title> <style> </style> </head> <body> <p style="text-indent:10px">Welcome to wikiHow, the most trusted how-to site on the internet. wikiHow is where trusted research and expert knowledge come together.</p> <p>Since 2005, wikiHow has helped billions of people learn how to solve problems large and small. We work with credentialed experts, a team of trained researchers, and a devoted community to create the most reliable, comprehensive and delightful how-to content on the Internet.</p> </body> </html>
-
4
Type the indenting code into the style area. So, we want every paragraph to begin with 10px of space, not just one. This means we’ll need to create a style for the paragraph tag (<p>) that automatically adds 10px of space to the beginning of the first word in each paragraph. We’ll also want to remove the text-indent property from our original example, as it won’t be needed anymore. The property should look like this:
<!DOCTYPE html> <html> <head> <title>wikiHow: How-to instructions you can trust.</title> <style> p { text:indent: 10px; </style> </head> <body> <p>Welcome to wikiHow, the most trusted how-to site on the internet. wikiHow is where trusted research and expert knowledge come together.</p> <p>Since 2005, wikiHow has helped billions of people learn how to solve problems large and small. We work with credentialed experts, a team of trained researchers, and a devoted community to create the most reliable, comprehensive and delightful how-to content on the Internet.</p> </body> </html>
- You can adjust the number of spaces by typing a different number after «text-indent:».
- You can use unites other than pixels to define the size of your indent, such as percentage (i.e. «text-indent: 15%;») or measurements (e.g., «text-indent: 3mm;»).
-
5
Type <p> at the beginning of each paragraph. Since we’ve added specific instructions to indent the <p> tag, every paragraph on the page will be indented 2.5em. This goes for our existing paragraphs, and any new paragraphs we add to the page.
Advertisement
Sample HTML Code
Add New Question
-
Question
If I define lines of text as individual paragraphs, I get a blank space between lines. How do I get rid of that space?
Use a line break instead of the paragraph break.
-
Question
Can I specify more than one CSS class for any HTML element?
Yes, it’s very simple too. Inside the class attribute, add all the classes you want the element to have, separated by a space. For example, if you had a tag needing the classes «blueFont» and «underline,» the class attribute would be:
class=»blueFont underline»
-
Question
How do I space HTML code vertically?
The most basic is to simply style it with margin and/or padding. Alternatively, read into absolutely positioning an element, then you can specify exactly where on the page you want in, pixel for pixel.
See more answers
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
-
If your spaces turn into strange symbols on the web browser, it’s most likely caused by extra data stored in the word processing format not intended for online display. Avoid this by using a plaintext editor like Notepad or TextEdit.
-
CSS is a much more powerful and predictable way to lay out your page, including the spacing of your text.
Thanks for submitting a tip for review!
Advertisement
About This Article
Article SummaryX
1. Type « » to add a single space.
2. Type «&ensp» to add 2 spaces.
3. Type «&emsp» to add 4 spaces.
4. Use the non-breaking space (nbsp) 4 times to insert a tab.
5. Use «br» to add a line break.
Did this summary help you?
Thanks to all authors for creating a page that has been read 5,926,131 times.
Is this article up to date?
Download Article
Download Article
Adding extra space between words and paragraphs in HTML is very different than in apps like Microsoft Word. But don’t tear out your hair just yet—we’ll show you the easiest ways to control spacing between words and lines of text, as well as how to add extra space to the beginning of each paragraph so they are properly indented on the page. This wikiHow article teaches you different ways you can add spaces to your HTML code.
-
1
Open your HTML code in a text editor. You can use any text editor, such as Notepad for Windows, or TextEdit for macOS, to edit your code. If you press the spacebar multiple times to add extra space between words or characters, you won’t see those extra spaces on your webpage—HTML automatically converts multiple spaces into a single space. You can fix this by using non-breaking space characters instead of pressing the spacebar.
-
2
Type where you want to insert an extra space. Add one non-breaking space character for every space you want to add. Unlike pressing the spacebar multiple times in your HTML code, typing more than once creates as many spaces as there are instances of .[1]
- For example, let’s say you want three spaces between the words «What will you learn» and «today?» Instead of pressing the spacebar three times, just type between the two segments. Here’s an example:
<!DOCTYPE html> <html> <head> <title>wikiHow: How-to instructions you can trust.</title> </head> <body> <p>What will you learn&nbsp;&nbsp;&nbsp;today?</p> </body> </html>
Basically, just translates to «one space» in HTML.
Advertisement
- For example, let’s say you want three spaces between the words «What will you learn» and «today?» Instead of pressing the spacebar three times, just type between the two segments. Here’s an example:
-
3
Use other spacing characters as shortcuts. If you want to insert two spaces, four spaces, or indent the beginning of a line, you don’t have to type multiple times:
- Two spaces: Type  
- Four spaces: Type  
Advertisement
-
1
Open your HTML code. Another way to add more spaces to your code is to use the HTML <pre> tag. This tag essentially displays the text exactly as you type or paste it, spaces and all. Start by opening your code in a text editor like Notepad for Windows or TextEdit for macOS.
-
2
Type <pre> </pre> tags in the body of your document. Any text you want to keep preformatted with a particular amount of spaces and/or line breaks will go between these tags:
<!DOCTYPE html> <html> <head> <title>wikiHow: How-to instructions you can trust.</title> </head> <body> <pre> </pre> </body> </html>
-
3
Type or paste text exactly as intended between the «<pre>» and »<pre>» tags. In this example, we’re creating three spaces between words, as well as a line break. When pre-formatting text, any spaces between words, as well as line breaks you create by pressing «Enter» or «Return,» will be displayed on the webpage.[2]
<!DOCTYPE html> <html> <head> <title>wikiHow: How-to instructions you can trust.</title> </head> <body> <pre>What will you learn today?</pre> </body> </html>
Advertisement
-
1
Open your HTML code in a text editor. Do you want to add extra space between paragraphs or other elements on the page? Pressing Enter or Return a bunch of times in your code won’t do the trick, but adding a line break tag <br> will! Start by opening the HTML code of the page you want to edit.
-
2
Type <br> on each line you want to make blank. For example, if you want to insert just one extra blank horizontal line between two paragraphs, you’d just type one <br> once. But if you wanted to add three line breaks, you could type it three times: <br><br><br>.
- In this example, we’re adding two lines of extra space between our sentences:
<!DOCTYPE html> <html> <head> <title>wikiHow: How-to instructions you can trust.</title> </head> <body> <pre>What will you learn today?</pre> <br><br> <p>You will learn a lot!</p> </body> </html>
- In this example, we’re adding two lines of extra space between our sentences:
Advertisement
-
1
Open an HTML document. Let’s say you want to indent the beginning a paragraph with some space—let’s say 10 pixels. The best way to do this would be to use CSS (Cascading Style Sheets). We’ll cover two ways to do this—one lets you indent each paragraph manually, and another indents all paragraphs at once. Start by opening up your HTML document in a text editor.
-
2
Indent a single paragraph. If we want to indent the paragraph in our example, we can do so by adding the text-indent property to its <p> tag. In this example, we’ll be indenting our paragraph by 10px:
<!DOCTYPE html> <html> <head> <title>wikiHow: How-to instructions you can trust.</title> </head> <body> <p style="text-indent:10px">Welcome to wikiHow, the most trusted how-to site on the internet. wikiHow is where trusted research and expert knowledge come together.</p> <p> Since 2005, wikiHow has helped billions of people learn how to solve problems large and small. We work with credentialed experts, a team of trained researchers, and a devoted community to create the most reliable, comprehensive and delightful how-to content on the Internet.</p> </body> </html>
- Since we added the text-indent property to just the first paragraph, that is the only paragraph that will be indented. Read on to learn how to indent all paragraphs on the page the same way instead of just one!
-
3
Create a style section for your CSS. If we want to indent all paragraphs on our page, we can do so by defining the paragraph style in CSS. The style section goes into the head of your HTML code, or on a separate style sheet. Let’s add ours to the head, which is between the <head> and </head> tags:
<!DOCTYPE html> <html> <head> <title>wikiHow: How-to instructions you can trust.</title> <style> </style> </head> <body> <p style="text-indent:10px">Welcome to wikiHow, the most trusted how-to site on the internet. wikiHow is where trusted research and expert knowledge come together.</p> <p>Since 2005, wikiHow has helped billions of people learn how to solve problems large and small. We work with credentialed experts, a team of trained researchers, and a devoted community to create the most reliable, comprehensive and delightful how-to content on the Internet.</p> </body> </html>
-
4
Type the indenting code into the style area. So, we want every paragraph to begin with 10px of space, not just one. This means we’ll need to create a style for the paragraph tag (<p>) that automatically adds 10px of space to the beginning of the first word in each paragraph. We’ll also want to remove the text-indent property from our original example, as it won’t be needed anymore. The property should look like this:
<!DOCTYPE html> <html> <head> <title>wikiHow: How-to instructions you can trust.</title> <style> p { text:indent: 10px; </style> </head> <body> <p>Welcome to wikiHow, the most trusted how-to site on the internet. wikiHow is where trusted research and expert knowledge come together.</p> <p>Since 2005, wikiHow has helped billions of people learn how to solve problems large and small. We work with credentialed experts, a team of trained researchers, and a devoted community to create the most reliable, comprehensive and delightful how-to content on the Internet.</p> </body> </html>
- You can adjust the number of spaces by typing a different number after «text-indent:».
- You can use unites other than pixels to define the size of your indent, such as percentage (i.e. «text-indent: 15%;») or measurements (e.g., «text-indent: 3mm;»).
-
5
Type <p> at the beginning of each paragraph. Since we’ve added specific instructions to indent the <p> tag, every paragraph on the page will be indented 2.5em. This goes for our existing paragraphs, and any new paragraphs we add to the page.
Advertisement
Sample HTML Code
Add New Question
-
Question
If I define lines of text as individual paragraphs, I get a blank space between lines. How do I get rid of that space?
Use a line break instead of the paragraph break.
-
Question
Can I specify more than one CSS class for any HTML element?
Yes, it’s very simple too. Inside the class attribute, add all the classes you want the element to have, separated by a space. For example, if you had a tag needing the classes «blueFont» and «underline,» the class attribute would be:
class=»blueFont underline»
-
Question
How do I space HTML code vertically?
The most basic is to simply style it with margin and/or padding. Alternatively, read into absolutely positioning an element, then you can specify exactly where on the page you want in, pixel for pixel.
See more answers
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
-
If your spaces turn into strange symbols on the web browser, it’s most likely caused by extra data stored in the word processing format not intended for online display. Avoid this by using a plaintext editor like Notepad or TextEdit.
-
CSS is a much more powerful and predictable way to lay out your page, including the spacing of your text.
Thanks for submitting a tip for review!
Advertisement
About This Article
Article SummaryX
1. Type « » to add a single space.
2. Type «&ensp» to add 2 spaces.
3. Type «&emsp» to add 4 spaces.
4. Use the non-breaking space (nbsp) 4 times to insert a tab.
5. Use «br» to add a line break.
Did this summary help you?
Thanks to all authors for creating a page that has been read 5,926,131 times.
Is this article up to date?
Здравствуйте, дорогие посетители!
Наверняка у каждого из вас возникали ситуации, когда при верстке вам нужно было разместить в блоке какой-либо текст, но он в него не вмещался, или наоборот, был слишком маленьким по объему, и в блоке оставалось слишком много пустого места.
В таких случаях можно попробовать различные методы выхода из положения. Например, можно поменять размер шрифта, урезать текст или изменить размер блока. Но если ни один из этих вариантов не подходят, то остается только поменять расстояние между буквами и расстояние между словами в CSS.
Чтобы изменить межбуквенный интервал в CSS мы можем использовать свойство letter-spacing. По умолчанию браузеры устанавливают межбуквенный интервал, основываясь на типе выбранного шрифта и его параметров. С помощью данного свойства мы можем задать расстояние между буквами для текста css в конкретном элементе.
Свойство letter-spacing может принимать три значения:
- Числовое значение – можно задать интервал в любых доступных для css единицах измерения (px, in, pt, em, ex), а так же можно задавать как положительные, так и отрицательные значения.
- normal – задает расстояние между буквами css для текста по умолчанию (0.25em)
- inherit – параметры межбуквенного интервала в css будут наследоваться от родительского элемента.
Например:
letter-spacing: 3px;
Как мы можем его использовать? Например, у меня четыре одинаковых блока с текстом, в оном блоке текст как раз подобран по размеру, а в остальных трех фрагменты текста значительно меньше, но изменить размеры блоков нельзя.
Для первых трех блоков можно попробовать увеличить расстояние между буквами css, и тем самым сделать его немного объемнее. В файле стилей, для абзацев в классах первых трех элементов пишем следующие свойства:
.row15 .first p, .row15 .second p, .row15 .third p{ letter-spacing:0.2ex; } |
В итоге вот что получилось:
Визуально видно, что расстояние между буквами увеличились, но этого не достаточно.
Интервал между буквами увеличивать больше не стоит, так как это отрицательно скажется на внешнем виде. Поэтому я попробую увеличить интервал между словами в css.
Как изменить расстояние между словами CSS?
Для этого мы можем использовать аналогичное свойство, которое называется word-spacing. Работает оно точно так же как и предыдущее с единственным отличием в том, что расстояние устанавливается для целых слов.
word-spacing может принимать такой же набор значений:
- Числовое значение – размер интервала может быть задан в пикселях, дюймах, пунктах и относительных единицах
- normal – значение по умолчанию
- inherit – наследование родительских параметров
Для тех же трех блоков задам расстояние между словами в css-файле:
.row15 .first p, .row15 .second p, .row15 .third p{ letter-spacing:0.2em; word-spacing:1em; } |
Вот что у меня получилось:
Используя данные свойства можно придать тексту дополнительный объем, но главное, конечно же, не перестараться. Так как слишком большие расстояние между словами или символами обязательно скажется на внешнем виде и читаемости текста. В любом случае нужно подбирать интервалы в зависимости от ситуации и используемого шрифта.
А на этом у меня сегодня все. Если данный материал был для вас полезен, делитесь статьей в социальных сетях и подписывайтесь на мою рассылку новостей сайта!
Удачи вам в оформлении страниц сайта! До встречи в следующих статьях!
С уважением Юлия Гусарь