Display inline block word wrap

I am trying to layout three divs inline next to each other. The last div could have a very long first word in its content, and when it does, it wraps to the next line. I want it to remain on the first line and wrap the word instead.

I have the following:

#container {
  width: 300px;
  display: inline-block;
}

#text1 {
  outline: 1px solid red;
  display: inline;
  margin-right: 5px;
}

#text2 {
  outline: 1px solid red;
  display: inline;
  margin-right: 5px;
}

#title-container {
  outline: 1px solid red;
  display: inline;
  overflow: hidden;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
  -ms-text-overflow: ellipsis;
  white-space: nowrap;
}

#title {
  white-space: pre-wrap;
  word-wrap: break-word;
  -ms-word-wrap: break-word;
  -ms-word-break: break-word;
}
<div id="container">
  <div id="text1">
    Text1
  </div>
  <div id="text2">
    12345
  </div>
  <div id="title-container">
    <span id="title">verryyyyyyyyyyyyyyyyyyyyyyyyyyyrrrrrrrrrrryyyyyyyyyyyyyy long title</span>
  </div>
</div>

Here is a fiddle demonstrating the problem.

https://jsfiddle.net/wzm3h6u6/

What is the correct fix here?

Julio Feferman's user avatar

asked Sep 27, 2017 at 23:59

Alex Bettadapur's user avatar

Just add word-break: break-all; css to #title-container

#container {
  width: 300px;
  display: inline-block;
}

#text1 {
  outline: 1px solid red;
  display: inline;
  margin-right: 5px;
}

#text2 {
  outline: 1px solid red;
  display: inline;
  margin-right: 5px;
}

#title-container {
  outline: 1px solid red;
  display: inline;
  overflow: hidden;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
  -ms-text-overflow: ellipsis;
  white-space: nowrap;
  word-break: break-all;
}

#title {
  white-space: pre-wrap;
  word-wrap: break-word;
  -ms-word-wrap: break-word;
  -ms-word-break: break-word;
}
<div id="container">
  <div id="text1">
    Text1
  </div>
  <div id="text2">
    12345
  </div>
  <div id="title-container">
    <span id="title">verryyyyyyyyyyyyyyyyyyyyyyyyyyyrrrrrrrrrrryyyyyyyyyyyyyy long title</span>
  </div>
</div>

answered Sep 28, 2017 at 6:57

Supraja Ganji's user avatar

Supraja GanjiSupraja Ganji

1,1871 gold badge6 silver badges8 bronze badges

1

To do this you need to add a width to your #title-container div so it knows which width to stay at rather than it being determined by its contents.

word-wrap: break-word; to wrap the text.
display: inline-block;
And finally vertical-align: top to align with the top of the container.

#title-container {
  outline: 1px solid red;
  display: inline-block;
  width: 40px;
  word-wrap: break-word;
  vertical-align: top;
}

See fiddle here

answered Sep 28, 2017 at 0:32

Coffee bean's user avatar

Coffee beanCoffee bean

1,47417 silver badges27 bronze badges

2

You can wrap a long string, which does not have any whitespace character by using the CSS word-wrap property, or overflow-wrap, if you use CSS3.

In this snippet, you’ll find some examples for block elements, as well as for the inline ones.

In the example below, we set the word-wrap property to its «break-word» value for the <span> element and specify its width. Also, we set the display property to “inline-block”.

Example of wrapping a long string without a whitespace character for inline elements:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      span {
        width: 135px;
        word-wrap: break-word;
        display: inline-block;
      }
    </style>
  </head>
  <body>
    <span>
      LoremIpsumLoremIpsumLoremIpsumLoremIpsumLoremIpsumLoremIpsumLoremIpsum
    </span>
  </body>
</html>

Result


LoremIpsumLoremIpsumLoremIpsumLoremIpsumLoremIpsumLoremIpsumLoremIpsum

Example of wrapping a long string without a whitespace character for block elements:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      textarea {
        width: 100px;
        word-wrap: break-word;
      }
    </style>
  </head>
  <body>
    <textarea>
      LoremIpsumLoremIpsumLoremIpsumLoremIpsumLoremIpsumLoremIpsumLoremIpsumLoremI
    </textarea>
  </body>
</html>

Here too, we specified the word-wrap and width properties, but for the <textarea> element.

In CSS3, the word-wrap property is renamed to overflow-warp. So, consider this when choosing the solution.

Example of wrapping a long string without a whitespace character with the CSS overflow-wrap property:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      span {
        display:inline-block;
        width: 150px;
        overflow-wrap: break-word;
      }
    </style>
  </head>
  <body>
    <span>
      LoremIpsumLoremIpsumLoremIpsumLoremIpsumLoremIpsumLoremIpsumLoremIpsum
    </span>
  </body>
</html>

Труднопереносимыми бывают не только люди, но и слова. К примеру, химическое соединение метилпропенилендигидроксициннаменилакрилическая кислота очень похожа на некоторых людей с «подвывертом»! Не знаем, как справляться с такими трудными личностями, но реализовать перенос текста CSS точно поможет.

  • Зачем переносить «непереносимое»
  • Решаем проблему переноса слов с помощью HTML
  • Как реализовать CSS перенос слов
  • Как реализовать запрет переноса слов CSS

В большинстве случаев при отображении текстового содержимого веб-страниц в браузере перенос слов не применяется. Если слово не вмещается целиком в область экрана, то по умолчанию оно полностью «переезжает» на следующую строчку.

Частичный перенос применяется лишь к длинным и сложным словам, состоящим из нескольких терминов и разделенных дефисом. Вот тут и возникают проблемы отображения этих слов на разных по диагонали экранах и в разных браузерах. При этом точно предугадать, как длинное слово будет «выглядеть» на клиентской стороне трудно, поэтому задавать переносы «вручную» бессмысленно:

Зачем переносить «непереносимое»

Перед тем, как рассмотреть CSS перенос слов , изучим возможности решения этой проблемы с помощью языка гипертекста.
Для этого в HTML имеется несколько вариантов:

  • Использование символа мягкого разрыва ­ — позволяет задать место разрыва сложного слова. При изменении размеров окна браузера на следующую строку переносится только часть длинного слова, стоящая после &shy, а после первой половины выводится знак переноса, похожий на дефис:
<body>
<p>Пример сложного химического соединения и текста - метилпропенилендигидрок&shy;сициннаменилакрилическая кислота</p>
</body>

Решаем проблему переноса слов с помощью HTML

  • Использование тега — элемент появился в HTML 5. Он также служит для указания браузеру места для разрыва сложного или длинного слова. Но в отличие от предыдущего спецсимвола этот тег не выводит в месте «разлома» знак переноса, что может негативно сказаться на читаемости всего текста:
<style>
wbr { display: inline-block; }
</style>
</head>
<body>
<p>метилпропенилен<wbr>дигидроксицинна<wbr>менилакрилическая кислота</p>
</body>

Решаем проблему переноса слов с помощью HTML - 2

В некоторых браузерах поддержка тега <wbr> реализована некорректно. В них он будет работать, если для него в коде CSS прописано свойство display со значением inline-block.

Перед тем, как реализовать CSS перенос слов, давайте рассмотрим несколько свойств, способных разрешить основную проблему:

  • word-wrap – описывает, как производить перенос слов, которые по длине не помещаются в установленные размеры контейнера. Сразу стоит предупредить, что с валидацией этого свойства возникают проблемы, и с реализацией его поддержки в CSS консорциум W3C еще не определился. Поэтому специализированные валидаторы при наличии word-wrap в коде будут выдавать ошибку:

Как реализовать CSS перенос слов

Тем не менее, это свойство «воспринимается» всеми современными браузерами и является эффективным решением проблемы переноса длинных слов. word-wrap принимает следующие значения:

  • normal – слова не переносятся;
  • break-word – автоматический перенос слов;
  • inherit – наследование значения родителя.

Пример, иллюстрирующий применение этого свойства:

<style>
.container{
background-color: rgb(204,204,204);
padding:10px;
width:200px;
}
.content{
word-wrap: break-word;
}
</style>
</head>
<body>
<div class="container">
<p class="content">метилпропенилендигидроксициннаменилакрилическая кислота</p>
</div>
</body>

Как реализовать CSS перенос слов - 2

В новой спецификации CSS свойство word-wrap было переименовано в overflow-wrap. Оба свойства принимают одинаковые значения. Но поддержка overflow-wrap пока реализована слабо, поэтому лучше использовать старую версию свойства:

Как видно на расположенном выше скриншоте, новое свойство поддерживается Google Chrome, но не поддерживается в IE. Поэтому overflow-wrap лучше не использовать того чтобы реализовать  CSS перенос слов.

  • word-break – устанавливает правила переноса строк внутри контейнера, если они не помещаются в него по ширине. Это новое свойство, и его поддержка была реализована в CSS3. Оно является валидным, но предназначено для работы со строками, поэтому перенос слов может производиться грамматически неправильно.

Свойство принимает три значения:

  • normal – используются правила переноса, установленные по умолчанию;
  • word-break – перенос строк осуществляется автоматически, чтобы слово поместилось в установленные по ширине размеры контейнера;
  • keep-all – отключает автоматический перенос слов в китайском, японском и корейском. Для остальных языков действие значения аналогично normal.

Пример:

<style>
   .content {
   font-size: 30px; 
    background: rgb(51,204,153);
    width: 170px;
    padding: 10px;
    word-break:break-all;
   }
  </style>
 </head>
 <body> 
  <div class="content">
   <p>Синхрофазотрон</p>
   <p>Обеспокоенное состояние</p>
   <p>Одиннадцатиклассница</p>
   <p>метоксихлордиэтиламинометилбутиламин</p>
  </div>
 </body>

hyphens – новое свойство, которое появилось с выходом CSS3. Оно устанавливает, как браузер будет осуществлять перенос слов в выводимом тексте. Свойство принимает несколько значений:

  • none – отключает CSS перенос слов;
  • manual (значение по умолчанию) – слова переносятся в тех участках текстового блока, где это задано с помощью тега <wbr> или мягкого переноса (­);
  • auto – браузер автоматически переносит слова на основе своих настроек.

Для корректной работы свойства в теге <html> или <p> должен присутствовать атрибут lang со значением «ru» (lang=»ru»).

Свойство поддерживается последними версиями IE, Opera и Firefox. Для каждого из них прописывается своя строчка CSS. Hyphens не поддерживается Google Chrome. Пример:

<style>
.container{
background-color: rgb(153,255,204);
padding:10px;
width:200px;
}
.content{
-webkit-hyphens: auto;
-moz-hyphens: auto;
-ms-hyphens: auto;
}
</style>
</head>
<body>
<div class="container">
<p class="content" lang="ru">метилпропенилендигидроксициннаменилакрилическая кислота</p>
</div>
</body>

Иногда нужно сделать так, чтобы строка отображалась полностью без разрыва. Запрет использовать  CSS перенос слов можно реализовать несколькими способами:

  • С помощью неразрывного пробела &nbsp, который устанавливается в местах переноса строки или слов;
  • Задав свойству white-space значение «nowrap» (white-space: nowrap).

Пример реализации:

<style>
.container{
background-color: rgb(153,255,204);
padding:10px;
width:200px;
}
.content{
-webkit-hyphens: auto;
-moz-hyphens: auto;
-ms-hyphens: auto;
}
.nowrap
{
white-space: nowrap;	
}
</style>
</head>
<body>
<div class="container">
<p>метилпропенилендигидроксициннаменилакрилическая кислота раз</p>
<p class="content" lang="ru">метилпропенилендигидроксициннаменилакрилическая два</p>
<p class="nowrap">метилпропенилендигидроксициннаменилакрилическая кислота три</p>
<p>метилпропенилендигидроксициннаменилакрилическая&nbsp;кислота&nbsp;четыри</p>
</div>
</body>

Как реализовать запрет переноса слов CSS

Теперь вы сможете переносить с помощью CSS даже самые длинные слова. Но вот с проблемой труднопереносимых людей вам придется разбираться самостоятельно. Попробуйте воздействовать на них методами CSS – может и получиться, хотя мы сами не проверяли.

Example of A Guide To CSS Text Wrapping

Note: This article is focused on the semantics of the English Language as the Writing System. Other systems, especially CJK (Chinese Japanese Korean) have conventions and overflow requirements that vary from English and are out of the scope of this article.

Text Wrapping

In CSS, overflow is the scenario when the content inside a fixed-width container, is wider than the container’s width. The default behavior of CSS is to render the content flowing out of the container. This may look ugly but this helps the developer see the issue and fix it — instead of the issue getting hidden which can cause potential missing information for the user. For example, a form submission button overflowing and becoming inaccessible. So to avoid such issues, CSS by default prevents Data Loss.

Content overflowwwwwwwwwww

CSS offers multiple capabilities to fix this issue.

Property: overflow-wrap (alias word-wrap)

This property applies to inline elements. It determines whether the browser should break an otherwise unbreakable string to avoid it from overflowing its parent’s width.

It has the following possible keyword values.

  1. normal
  2. Anywhere
  3. break-word

overflow-wrap: normal

When set to normal, the browser will break the string on default/natural opportunities, such as a blank space or a hyphen (‘-’) character. It will also leverage soft-hyphen entity &shy; to break.
This is the initial value of the overflow-wrap property. So by default, every string will be broken at soft wrap opportunities, if any, on overflow.

This is how ‘ContentOverflowing’ and ‘Content-Overflowing’ will be handled.

ContentOverflowing

Content-Overflowing

overflow-wrap: anywhere;

This value allows the browser to break the string anywhere to avoid overflow.

Consider the following scenario with the default overflow-wrap: normal; value for a fixed-width container.

ContentOverflow

There is no blank space, a hyphen, or any other soft wrap opportunity in the string. Therefore, it overflows. If we apply overflow: anywhere;, we get the following, wrapped result.

ContentOverflow

overflow-wrap: break-word;

It behaves the same as overflow-wrap: anywhere;. The difference is that the former does not consider soft-wrap opportunities when calculating min-content intrinsic sizes. In case you have not explored extrinsic vs intrinsic sizing, Ahmed Shadeed provides a great resource. It breaks only those words which have a width smaller than the available width.

Content is Overflowing

Property: word-break

CSS offers another property, word-break for handling the same issue — overflows.

It has the following keyword values

  1. normal
  2. break-all
  3. keep-all
  4. break-word

word-break: normal;

Words will break at the default rules — such as a blank space, a hyphen, etc.

This is how ‘ContentOverflow’ and ‘Content-Overflow’ will be handled.

ContentOverflow

Content-Overflow

word-break: break-all;

Break the word at the point it overflows. It does not take into account if placing the overflowing word onto the next line will eliminate the overflow in the first place or not. This doesn’t apply to CJK writing systems.

ContentOverflow

word-break: keep-all;

For Non-CJK systems, the behavior is the same as word-break: normal.

ContentOverflow

word-break: break-word;

It has the same effect that word-break: normal; and overflow-wrap: anywhere; has. But unlike word-break: break-all; , it takes into account if placing the overflowing word onto the next line will eliminate the overflow. 

For example, let’s see how word-break: break-word; handles the following scenario:

Content is Overflowing Again

We observe that the whole word ‘Overflowing’ was moved onto the next line instead of breaking as it can fit the available width without overflowing. If we apply word-break: break-all; to it, this is what we get:

Content is Overflowing Again

The word ‘Overflowing’ was broken at exactly the point where it otherwise caused the overflow. And it was not considered if moving it onto the next line eliminated the overflow or not.

overflow-wrap vs word-break

At a high level, both properties solve the same issue. But, a key difference lies in how both the properties approach the issue and the subtle aesthetic variation in their outcomes.

To visualize, consider a fixed and short-width container for the test “A Very LongWordThatHasNoBreakingPossibilities”.

A Very LongWordThatHasNoBreakingPossibilities

Let’s solve the overflow with overflow-wrap: break-word;.

A Very LongWordThatHasNoBreakingPossibilities

Now, let’s solve it with word-break: break-all;.

A Very LongWordThatHasNoBreakingPossibilities

Notice the difference? word-break: break-all; breaks the word even if placing the word on the next line would eliminate the need for breaking. This prevents large gaps before the breaks — and produces visually better results. The difference is more clearly visible in the overflow-wrap: anywhere; vs word-break: break-all; case. A case of the apparently twin properties. Consider you have a very short space to squeeze in a checkbox and a text which can not fit on the same line without overflowing. This is how the outcome looks like with overflow-wrap: anywhere;:

Photosynthesis

We observe that a lot of real estate beside the checkbox has been left unutilized. A better fix is provided by word-break: break-all;:

Photosynthesis

As observed, word-break discards the possibility of the word fitting the next line and prefers optimizing the usage of available real estate — this is often the better adjustment visually.
The above example receives its inspiration from MDN’s resource on text wrapping.

Summary

This table shows a summary of the CSS text wrapping properties

Property Value Behavior When To Use Example
overflow-wrap

normal

Break at natural line breakpoints such as blank space, a hyphen When overflow is determined to not be a possibility

Content

anywhere Break between any 2 characters where the overflow occurs and consider soft wrap opportunities when calculating the min-content intrinsic sizes When overflow should be handled by breaking long words. As discussed, the alternative option of word-break: break-all; produces visually better results

ContentOverflow

break-word Break between any 2 characters but do not consider soft wrap opportunities when calculating the min-content intrinsic sizes When overflow should be handled by breaking only those words which have a width smaller than the available width

Content is Overflowing

word-break normal Break at default rules When overflow is determined to not be a possibility

Content

break-all Break exactly where the content overflows When overflow should be handled by breaking text exactly at the point of overflow — even if placing the word on a new line eliminates the overflow

Content is Overflowing Again

break-word Same as word-break: normal; and overflow-wrap: anywhere; — Break can create gaps unlike word-break: break-all; When placing the overflowing word onto the next line eliminates overflow. This can cause gaps.

Content is Overflowing Again

Examples

Here are examples from the above summary in a codepen to help demonstrate what the CSS code should look like:

<section class="centered">
  <h2>Without Handling Overflow</h2>
<div>Content with aVeryVeryVeryLongWord</div>
<!---->

<h2>Handling Overflow with overflow-wrap</h2>
  
<h3>overflow-wrap: normal;</h3>
<div class="ow-normal">Content with aVeryVeryVeryLongWord</div>
  
<h3>overflow-wrap: anywhere;</h3>
<div class="ow-anywhere">Content with aVeryLongWordThatDoesNotFit</div>
  
<h3>overflow-wrap: break-word;</h3>
<div class="ow-break-word">Content with aVeryLongWordThatDoesNotFit</div>
<!---->

<h2>Handling Overflow with word-break</h2>
  
   
<h3>word-break: normal;</h3>
<div class="wb-normal">Content with aVeryVeryVeryLongWord</div>
  
<h3>word-break: break-all;</h3>
<div class="wb-break-all">Content with aVeryLongWordThatDoesNotFit</div>
  
<h3>word-break: break-word;</h3>
<div class="wb-break-word">Content with aVeryLongWordThatDoesNotFit</div>
</section>
* { font-family: sans-serif; }

section.centered { text-align: center; }

div {
  display: inline-block;
  width: 130px;
  border: 3px solid #48abe0;
  text-align: left;
}

.ow-normal {
  overflow-wrap: normal;
}

.ow-anywhere {
  overflow-wrap: anywhere;
}

.ow-break-word {
  overflow-wrap: break-word;
}

.wb-normal {
  word-break: normal;
}

.wb-break-all {
  word-break: break-all;
}

.wb-break-word {
  word-break: break-word;
}

h3 {
  font-weight: normal;
  font-style: italic;
  border-top: 1px solid #b5b5b5;
  width: 30%;
  margin-left: auto;
  margin-right: auto;
  margin-top: 20px;
  padding-top: 20px;
}

Conclusion

This article has scratched the surface of text-wrapping. Wrapping in itself is a deeper topic as it is tightly coupled to the semantics of the target language. Moreover, it is becoming common to offer web content in multiple languages — aka Internatiolaisation/ Localisation — which makes learning it more important than before for the developers.

null

Перенос длинных слов

Проблема переноса длинных слов встречается не так редко, как может показаться. Если не брать во внимание слова-рекордсмены вроде “метилпропенилендигидроксициннаменилакрилической кислоты”, порой в установленные макетом страницы рамки не умещаются менее экзотические слова.

Браузеры по умолчанию не разбивают длинные слова на несколько строк. Перенос на новую строку происходит только там, где стоит дефис, пробел или Enter (исключение составляют неразрывный пробел &nbsp; и неразрывный дефис ‑). При некоторых условиях может появиться ползунок горизонтальной прокрутки, но чаще всего слово выйдёт за границы отведённого ему блока.

Немного иначе ведут себя flexbox элементы и таблицы, они игнорируют установленную ширину и всегда растягиваются настолько, чтобы вместить текст целиком. В примере ниже flex-контейнеру было задано ограничение по ширине (width: 300px;), однако видно, что в зависимости от контента блок может занимать больше места. Не самая приятная особенность для верстальщика, уверенного, что в его макете всё рассчитано до пикселя.

Перенос слов средствами HTML

Как говорилось выше, по умолчанию браузер не переносит слова на несколько строк. Отчасти потому, что он может не знать, как это сделать грамотно.

Указать браузеру, в каких местах слово может быть разбито переносом можно с помощью символа мягкого разрыва (&shy;). Переносы будут добавлены только там и тогда, когда это необходимо, чтобы слово поместилось в контейнер.

В HTML5 появился тег <wbr/>, обладающий схожим эффектом, однако он не добавляет символ переноса в месте разрыва слова, что выглядит уже не так красиво.

<html>
  <head>
    <style>
      .card {
        width: 200px;
        height: 250px;
        background: #7cd4ae;
        padding: 10px;
        display: inline-block;
        margin: 2em;
      }
    </style>
  </head>

  <body>
    <div class="card">
      <img src="troll.jpg">
      Двухсот&shy;восьмидесяти&shy;восьми&shy;киллограммовый тролль
    </div>
    <div class="card">
      <img src="troll.jpg">
      Двухсот<wbr/>восьмидесяти<wbr/>восьми<wbr/>киллограммовый тролль
    </div>
  </body>
</html>

Перенос слов средствами CSS

В CSS есть несколько свойств, влияющих на перенос текста.

  • overflow-wrap (word-wrap) — управляет переносом длинных слов (normal — не переносить, если перенос не задан явно, break-word — принудительно переносить).
  • word-break — управляет переносом длинных слов (normal — не переносить, если перенос не задан явно, break-all — принудительно переносить, keep-all — не переносить, даже если слово содержит дефис).
  • hyphens — автоматический перенос слов, основанный на встроенном в браузер словаре переносов (none — не переносить, auto — переносить длинные слова).

Название word-wrap является устаревшим, но сохраняется для совместимости со старыми версиями браузеров.

Свойства word-wrap и word-break на первый взгляд делают одно и то же, но есть небольшие отличия. Word-wrap считается более общим, тогда как word-break предусматривает специальное поведение для китайского, японского и корейского языков. Word-wrap начинает не поместившееся слово с новой строки, а word-break нет. Однако word-break является более приоритетным по отношению к word-wrap.

Свойство hyphens является наиболее мощным и удобным, но его поддержка браузерами пока не идеальна. Плюс оно требует обязательного указания языка в атрибуте lang тега (например, lang=»ru»).

<html>
  <head>
    <style>
      .description {
        width: 100px;
        background: #7cd4ae;
        word-wrap: break-word;
        word-break: break-all; /* более приоритетно */
      }
    </style>
  </head>

  <body>
    <div class="description" lang="ru">
      Верховный суд Лос-Анджелеса решит судьбу огромнейшего трёхсотвосьмидесятикилограммового изумруда
    </div>
  </body>
</html>

Понравилась статья? Поделить с друзьями:
  • Display file name excel
  • Display count in excel
  • Display code in word
  • Display all fonts in word
  • Display all excel formulas