white-space

white-space

normal Текст в окне браузера выводится как обычно, переносы строк устанавливаются автоматически. nowrap Пробелы не учитываются, переносы строк в коде HTML игнорируются, весь текст отображается одной строкой; вместе с тем, добавление тега
переносит текст на новую строку. pre Текст показывается с учетом всех пробелов и переносов, как они были добавлены разработчиком в коде HTML. Если строка получается слишком длинной и не помещается в окне браузера, то будет добавлена горизонтальная полоса прокрутки. pre-line В тексте пробелы не учитываются, текст автоматически переносится на следующую строку, если он не помещается в заданную область. pre-wrap В тексте сохраняются все пробелы и переносы, однако если строка по ширине не помещается в заданную область, то текст автоматически будет перенесен на следующую строку. inherit Наследует значение родителя.

Действие значений на текст представлено в табл. 1.

Табл. 1. Перенос текста и пробелы при разных значениях white-space

Значение Перенос текста Пробелы
normal Переносится Не учитываются
nowrap Не переносится Не учитываются
pre Не переносится Учитываются
pre-line Переносится Не учитываются
pre-wrap Переносится Учитываются

HTML5 CSS2.1 IE Cr Op Sa Fx

        

Результат данного примера показан на рис. 1.

Применение свойства white-space

Рис. 1. Применение свойства white-space

Объектная модель

[window.]document.getElementById(» elementID «).style.whiteSpace

Браузеры

Браузер Internet Explorer до версии 7.0 включительно не поддерживает значения pre-line , pre-wrap и inherit . Для значения normal и pre ведут себя как pre-wrap , а значение nowrap ведет себя как pre-line .

Opera до версии 9.5 не поддерживает значение pre-line . Для значения normal и pre ведут себя как pre-wrap , а значение nowrap ведет себя как pre-line .

Safari до версии 3.0 и iOS не поддерживают значения pre-wrap и pre-line .

Firefox до версии 2.0 включительно не поддерживает значения pre-line и pre-wrap . Для значения normal , nowrap , и pre воспринимаются как pre-wrap .

Источник

white-space

normal Текст в окне браузера выводится как обычно, переносы строк устанавливаются автоматически. nowrap Пробелы не учитываются, переносы строк в коде HTML игнорируются, весь текст отображается одной строкой; вместе с тем, добавление тега
переносит текст на новую строку. pre Текст показывается с учетом всех пробелов и переносов, как они были добавлены разработчиком в коде HTML. Если строка получается слишком длинной и не помещается в окне браузера, то будет добавлена горизонтальная полоса прокрутки. pre-line В тексте пробелы не учитываются, текст автоматически переносится на следующую строку, если он не помещается в заданную область. pre-wrap В тексте сохраняются все пробелы и переносы, однако если строка по ширине не помещается в заданную область, то текст автоматически будет перенесен на следующую строку. inherit Наследует значение родителя.

Действие значений на текст представлено в табл. 1.

Табл. 1. Перенос текста и пробелы при разных значениях white-space

Значение Перенос текста Пробелы
normal Переносится Не учитываются
nowrap Не переносится Не учитываются
pre Не переносится Учитываются
pre-line Переносится Не учитываются
pre-wrap Переносится Учитываются

HTML5 CSS2.1 IE Cr Op Sa Fx

        

Результат данного примера показан на рис. 1.

Применение свойства white-space

Рис. 1. Применение свойства white-space

Объектная модель

[window.]document.getElementById(» elementID «).style.whiteSpace

Браузеры

Браузер Internet Explorer до версии 7.0 включительно не поддерживает значения pre-line , pre-wrap и inherit . Для значения normal и pre ведут себя как pre-wrap , а значение nowrap ведет себя как pre-line .

Opera до версии 9.5 не поддерживает значение pre-line . Для значения normal и pre ведут себя как pre-wrap , а значение nowrap ведет себя как pre-line .

Safari до версии 3.0 и iOS не поддерживают значения pre-wrap и pre-line .

Firefox до версии 2.0 включительно не поддерживает значения pre-line и pre-wrap . Для значения normal , nowrap , и pre воспринимаются как pre-wrap .

Источник

How To Prevent Line Breaks Using CSS

How To Prevent Line Breaks Using CSS

Developers typically like to wrap text on a web page. Wrapping constrains text in one way or another and prevents design issues. Text wrapping can also prevent horizontal scrolling. But there are times when you want blocks of text to stay on the same line, regardless of length. You can prevent line breaks and text wrapping for specific elements using the CSS white-space property.

In this tutorial, you will style the same block of text four different ways, first with line breaks and then three times without line breaks:

Medusafish banded killifish convict blenny saury threadsail beluga sturgeon. Indian mul mora cisco masu salmon, roosterfish requiem shark longnose lancetfish bluefish red snapper Sacramento splittail giant danio.

Medusafish banded killifish convict blenny saury threadsail beluga sturgeon. Indian mul mora cisco masu salmon, roosterfish requiem shark longnose lancetfish bluefish red snapper Sacramento splittail giant danio.

Medusafish banded killifish convict blenny saury threadsail beluga sturgeon. Indian mul mora cisco masu salmon, roosterfish requiem shark longnose lancetfish bluefish red snapper Sacramento splittail giant danio.

Medusafish banded killifish convict blenny saury threadsail beluga sturgeon. Indian mul mora cisco masu salmon, roosterfish requiem shark longnose lancetfish bluefish red snapper Sacramento splittail giant danio.

This will provide you several options for wrapping or not wrapping your text.

Prerequisites

To complete this tutorial, you will need:

  • A code editor of your choice, such as nano or Visual Studio Code
  • A web browser
  • A comfort with HTML fundamentals. You can view our tutorial series How To Build a Website with HTML for an introduction.

Step 1 — Preventing and Forcing Line Breaks in CSS

In this step, you will create a style sheet with three different classes. Each one will handle line breaks differently: the first will break text in the default manner while the second and third will force the text not to create a newline and break.

First, create and open a new file called main.css using nano or your preferred editor:

Add the following content, which will introduce three CSS classes that use several properties, including white-space :

.sammy-wrap  border-radius: 6px; background-color: aliceblue; border: 2px dashed gray; max-width: 70%; padding: 1em; margin-bottom: .4em; > .sammy-nowrap-1  border-radius: 6px; background-color: aliceblue; border: 2px dashed gray; max-width: 70%; padding: 1em; margin-bottom: .4em; white-space: nowrap; > .sammy-nowrap-2  border-radius: 6px; background-color: aliceblue; border: 2px dashed gray; max-width: 70%; padding: 1em; margin-bottom: .4em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; > 

Your first class is .sammy-wrap . It defines six common CSS properties including border-radius , background-color , border max-width , padding , and margin-bottom . This class will create a visual box, but it does not define any special wrapping properties. This means it will break lines in the default manner.

Your second class is .sammy-nowrap-1 . It defines the same box as .sammy-wrap but now you add another property: white-space . The white-space property has numerous options, all of which define how to treat white space inside a given element. Here, you have set white-space to nowrap , which will prevent all line breaks.

Your third class is .sammy-nowrap-2 . It adds white-space and two additional properties: overflow and text-overflow . The overflow property handles scrollable overflow , which occurs when the contents inside an element extend beyond that element’s edges. The overflow property can make that content scrollable, visible, or hidden. You are setting overflow to hidden and then using the text-overflow property to add even more customization. text-overflow can help you signal to a user that additional text remains hidden. You have set this to ellipsis , so now your line will neither break nor extend beyond the box. CSS will hide the overflow and signal the hidden content with a . .

Now that you have a stylesheet, you are ready to make a short HTML file with some sample text. Then you will load the webpage in a browser and inspect how CSS can prevent line breaks.

Step 2 — Creating the HTML File

With your CSS classes defined, you can apply them to some sample text.

Create and open a file called index.html in your preferred editor. Make sure to place it in the same folder as main.css :

Add the following content, which will associate main.css as your stylesheet and then apply your classes to a sample text block:

DOCTYPE HTML> html> head> meta charset="UTF-8"> title>How To Prevent Line Breaks with CSStitle> link href="main.css" rel="stylesheet"> head> body> p class="sammy-wrap" > Medusafish banded killifish convict blenny saury threadsail beluga sturgeon. Indian mul mora cisco masu salmon, roosterfish requiem shark longnose lancetfish bluefish red snapper Sacramento splittail giant danio.p> p class="sammy-nowrap-1"> Medusafish banded killifish convict blenny saury threadsail beluga sturgeon. Indian mul mora cisco masu salmon, roosterfish requiem shark longnose lancetfish bluefish red snapper Sacramento splittail giant danio.p> p class="sammy-nowrap-2"> Medusafish banded killifish convict blenny saury threadsail beluga sturgeon. Indian mul mora cisco masu salmon, roosterfish requiem shark longnose lancetfish bluefish red snapper Sacramento splittail giant danio.p> p class="sammy-wrap" > Medusafish ;banded ;killifish ;convict ;blenny ;saury ;threadsail ;beluga ;sturgeon. ;Indian ;mul ;mora ;cisco ;masu ;salmon, ;roosterfish ;requiem ;shark ;longnose ;lancetfish ;bluefish ;red ;snapper ;Sacramento ;splittail ;giant ;danio.p> body> html> 

You have assigned your standard wrapping style to the first text block, your nowrap style to the second, and nowrap that is hidden with ellipsis to the third. You have assigned sammy-wrap to the fourth sample, but you are overriding the default wrapping by inserting non-breaking spaces (   ) directly into the HTML. If you need to prevent line-breaks as a one-off situation, then non-breaking spaces can provide a quick solution.

Open index.html in a web browser and view your results. Your four text blocks will appear like this:

Medusafish banded killifish convict blenny saury threadsail beluga sturgeon. Indian mul mora cisco masu salmon, roosterfish requiem shark longnose lancetfish bluefish red snapper Sacramento splittail giant danio.

Medusafish banded killifish convict blenny saury threadsail beluga sturgeon. Indian mul mora cisco masu salmon, roosterfish requiem shark longnose lancetfish bluefish red snapper Sacramento splittail giant danio.

Medusafish banded killifish convict blenny saury threadsail beluga sturgeon. Indian mul mora cisco masu salmon, roosterfish requiem shark longnose lancetfish bluefish red snapper Sacramento splittail giant danio.

Medusafish banded killifish convict blenny saury threadsail beluga sturgeon. Indian mul mora cisco masu salmon, roosterfish requiem shark longnose lancetfish bluefish red snapper Sacramento splittail giant danio.

You have successfully customized your CSS properties to prevent or allow line breaks in four different fashions.

Conclusion

In this tutorial, you used CSS to prevent line breaks on a block of text. You styled the text inside a box and then added the white-space property to override the default text wrapping. To learn more about handling text wrapping and white space, consider exploring the entire white-space CSS property.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Читайте также:  Тег AREA, атрибут alt
Оцените статью