Break word with hyphen

I want to break the long word with the hyphen at the end of the first line.

Expected:

BERUFSBILDUNGSZENT-
RUM

Got this:

BERUFSBILDUNGSZENT
RUM

Here’s my html and css:

<div class="content">BERUFSBILDUNGSZENTRUM</div>

.content {
  max-height: 80px;
  width: 200px;
  overflow-x: hidden;
  word-wrap: break-word;
  padding: 10px;
  -webkit-hyphens: auto;
  -moz-hyphens: auto;
  -ms-hyphens: auto;
  hyphens: auto;
  font-weight: bold;
  font-size: 16px;
  border: solid 1px #000;
}

You can check my JSFiddle

asked Mar 9, 2017 at 2:52

Lee's user avatar

4

Chrome does not do hyphenation apparently (at least on Windows). You may fare better with other browsers or platforms. You can use &shy; (soft hyphen) if you know in advance where you want to break. Otherwise, at least in Chrome on Windows there’s no way to get a hyphen when CSS breaks a long word, unless it was in the input to start with.

.content {
  max-height: 80px;
  width: 200px;
  overflow-x: hidden;
  word-wrap: break-word;
  padding: 10px;
  font-weight: bold;
  font-size: 16px;
  border: solid 1px #000;
}
Using soft hyphen:
<div class="content">BERUFSBILDUNGSZEN&shy;TRUM</div>    

Using automatic hyphenation (doesn't work in Chrome)
<div class="content" lang="de" style="hyphens: auto; ">BERUFSBILDUNGSZENTRUM</div>

Soft hyphen not displayed if it doesn't break there
<div class="content" style="width: 400px; ">BERUFSBILDUNGSZEN&shy;TRUM</div>

See also this answer.

Community's user avatar

answered Mar 9, 2017 at 3:14

4

Solution in 2022:

If you add the lang Attribute to your div and type out «Berufsbildungszentrum» cased normally, using hyphens: auto; does work as excpected. You can then uppercase the word again using text-transform: uppercase;.

Please note that the supported dictionaries for hyphenation differ from browser to browser. A compatibility table can be seen here.

.content {
  max-height: 80px;
  width: 200px;
  overflow-x: hidden;
  padding: 10px;
  -webkit-hyphens: auto;
  -moz-hyphens: auto;
  -ms-hyphens: auto;
  hyphens: auto;
  font-weight: bold;
  font-size: 16px;
  text-transform: uppercase;
  border: solid 1px #000;
}
<div lang="de" class="content">Berufsbildungszentrum</div>

Check also the updated JSFiddle

answered Mar 28, 2022 at 13:48

maku's user avatar

makumaku

1693 silver badges4 bronze badges

9

Add the lang="de" Attribute to your HTML-Tag, as the browser is deciding this using an algorithm which is decided on that language Tag.

Hakan Fıstık's user avatar

Hakan Fıstık

16.3k12 gold badges106 silver badges130 bronze badges

answered Mar 9, 2017 at 3:16

evayly's user avatar

evaylyevayly

8127 silver badges16 bronze badges

3

This guide explains the various ways in which overflowing text can be managed in CSS.

What is overflowing text?

In CSS, if you have an unbreakable string such as a very long word, by default it will overflow any container that is too small for it in the inline direction. We can see this happening in the example below: the long word is extending past the boundary of the box it is contained in.

CSS will display overflow in this way, because doing something else could cause data loss. In CSS data loss means that some of your content vanishes. So the initial value of overflow is visible, and we can see the overflowing text. It is generally better to be able to see overflow, even if it is messy. If things were to disappear or be cropped as would happen if overflow was set to hidden you might not spot it when previewing your site. Messy overflow is at least easy to spot, and in the worst case, your visitor will be able to see and read the content even if it looks a bit strange.

In this next example, you can see what happens if overflow is set to hidden.

Finding the min-content size

To find the minimum size of the box that will contain its contents with no overflows, set the width or inline-size property of the box to min-content.

Using min-content is therefore one possibility for overflowing boxes. If it is possible to allow the box to grow to be the minimum size required for the content, but no bigger, using this keyword will give you that size.

Breaking long words

If the box needs to be a fixed size, or you are keen to ensure that long words can’t overflow, then the overflow-wrap property can help. This property will break a word once it is too long to fit on a line by itself.

Note: The overflow-wrap property acts in the same way as the non-standard property word-wrap. The word-wrap property is now treated by browsers as an alias of the standard property.

An alternative property to try is word-break. This property will break the word at the point it overflows. It will cause a break-even if placing the word onto a new line would allow it to display without breaking.

In this next example, you can compare the difference between the two properties on the same string of text.

This might be useful if you want to prevent a large gap from appearing if there is just enough space for the string. Or, where there is another element that you would not want the break to happen immediately after.

In the example below there is a checkbox and label. Let’s say, you want the label to break should it be too long for the box. However, you don’t want it to break directly after the checkbox.

Adding hyphens

To add hyphens when words are broken, use the CSS hyphens property. Using a value of auto, the browser is free to automatically break words at appropriate hyphenation points, following whatever rules it chooses. To have some control over the process, use a value of manual, then insert a hard or soft break character into the string. A hard break () will always break, even if it is not necessary to do so. A soft break (&shy;) only breaks if breaking is needed.

You can also use the hyphenate-character property to use the string of your choice instead of the hyphen character at the end of the line (before the hyphenation line break).

This property also takes the value auto, which will select the correct value to mark a mid-word line break according to the typographic conventions of the current content language.

The <wbr> element

If you know where you want a long string to break, then it is also possible to insert the HTML <wbr> element. This can be useful in cases such as displaying a long URL on a page. You can then add the property in order to break the string in sensible places that will make it easier to read.

In the below example the text breaks in the location of the <wbr>.

See also

  • The HTML <wbr> element
  • The CSS word-break property
  • The CSS overflow-wrap property
  • The CSS white-space property
  • The CSS hyphens property
  • Overflow and Data Loss in CSS

Веб-пространство построено на контенте, а контент состоит из слов, и возможно из очень длинных. Всем «участникам» всемирной паутины рано или поздно приходится иметь дело с длинными словами:

Пример

Каждый день в сети я встречаю практически все виды дефектов отображения, связанных с длинными словами – «сломанные» макеты, обрезку слов и ситуацию, которая приведена на изображении выше.

  • Переносы
    • word-break
    • Overflow-wrap
    • Эллипсис
    • Заключение
    • Окончательное решение

Первое решение для длинных слов — это применение переносов.

Переносы

Пример

.hyphens {
  -webkit-hyphens: auto;
  -moz-hyphens: auto;
  -ms-hyphens: auto;
  hyphens: auto;
}

Поддержка браузерами: CSS-переносы поддерживаются во всех популярных браузерах, за исключением браузеров, реализованных на основе движка Blink (Chrome, Opera, Android). Здесь описаны все распространенные ошибки в Chrome. Я также протестировал Safari 5.1 под Windows, в котором переносы поддерживаются, но для моих тестовых слов все они добавлялись не в тех местах, в которых нужно.

Кроме этого, переносы во многом зависят от правил языка. Вам нужно определить атрибут lang в родительском элементе. Также нужно помнить, что другие языки, кроме английского, поддерживаются в браузерах на весьма низком уровне.

Вы также можете использовать библиотеку JavaScript, такую как Hyphenator.js, которая работает со многими языками и многими браузерами. Недостатком этого решения является то, что вам нужно будет загружать много дополнительных скриптов JavaScript, что может существенно снизить производительность.

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

word-break

Пример

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

Поддержка браузерами: Свойство CSS word-break поддерживается во всех браузерах, за исключением Opera Mini и старых браузеров Opera на основе Presto.

Еще одно возможное решение данной проблемы — использование word-wrap (overflow-wrap). Еще одно свойство, которое указывает, может ли браузер разбивать строки внутри слов:

Overflow-wrap

Пример

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

Поддержка браузерами: Свойство CSS word-wrap поддерживается во всех браузерах. В некоторых из них для нормальной работы требуется указывать унаследованное имя word-wrap (а не overflow-wrap).

Еще один вариант для решения проблемы длинных слов — это усечение:

Эллипсис

Пример

.ellipsis {
  overflow:hidden; 
  white-space: nowrap;
  text-overflow: ellipsis;
}

Поддержка браузерами: Text-overflow поддерживается во всех основных браузерах.

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

Пожалуйста, не используйте text-overflow: ellipsis, потому что сокращать слова — это не работа CSS. Только, если вам действительно необходимо это сделать на стороне сервера, и только после полного сокращения слов.

Я проверил все приведенные выше примеры и их сочетания в следующих браузерах: IE7, IE8, IE9, IE10, IE11, Edge, Firefox 39 (Windows, Linux, Mac), Chrome 44 (Windows, Linux, Mac), Opera 30 (Windows, Mac) , Safari 8 (Mac), Safari 5.1 (Windows), Android-5 (Nexus 6), Android 4.4 (Nexus 5), Android 2.3 (Galaxy S2), IOS 8.3 (iPhone 6), IOS 7 (iPhone 5S), IOS 6 (iPhone5), Opera Mini (Android 5), Opera Classic (Android 5), Opera Mobile (Android 5) и Windows Phone 8.1 (Lumia 930), используя реальные устройства и BrowserStack. По этой ссылке вы найдете список всех 26-браузеров, по этой ссылке — результаты их тестирования.

В интернете можно найти и такое решение:

.hyphenate {
  -ms-word-break: break-all;
  word-break: break-all;
  word-break: break-word;
  -webkit-hyphens: auto;
  -moz-hyphens: auto;
  hyphens: auto;
}

Хотя это прекрасно работает в большинстве случаев, я выяснил, что в Firefox перенос не будет работать (хотя он и поддерживается) в сочетании с word-break. Как и word-break, это свойство не поддерживается, и не будет работать в Opera Mini.

В то же время overflow-wrap прекрасно поддерживается браузерами. Я протестировал следующее решение, используя overflow-wrap и перенос.

.hyphenate {
  overflow-wrap: break-word
  word-wrap: break-word;
  -webkit-hyphens: auto;
  -ms-hyphens: auto;
  -moz-hyphens: auto;
  hyphens: auto;
}

Этот код выводит переносы во всех браузерах, в которых они поддерживаются, и разрывы строк во всех остальных. Хотя я и протестировал это решение в 26 различных браузерах, но до сих пор не уверен, что оно будет работать в 100% случаев — если вы найдете какое-нибудь исключение, пожалуйста, дайте знать об этом в комментариях к статье.

DigitalOcean provides cloud products for every stage of your journey. Get started with $200 in free credit!

The word-break property in CSS can be used to change when line breaks ought to occur. Normally, line breaks in text can only occur in certain spaces, like when there is a space or a hyphen.

In the example below we can make the word-break between letters instead:

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

If we then set the width of the text to one em, the word will break by each letter:

See the Pen Setting text vertically with word-break by CSS-Tricks (@css-tricks) on CodePen.

This value is often used in places with user generated content so that long strings don’t risk breaking the layout. One very common example is a long copy and pasted URL. If that URL has no hyphens, it can extend beyond the parent box and look bad or worse, cause layout problems.

See the Pen Fixing links with word-break by CSS-Tricks (@css-tricks) on CodePen.

Values

  • normal: use the default rules for word breaking.
  • break-all: any word/letter can break onto the next line.
  • keep-all: for Chinese, Japanese and Korean text words are not broken. Otherwise this is the same as normal.

This property is also often used in conjunction with the hyphens property so that when breaks occur a hypen is inserted, as per the standard in books.

The full usage, with needed vendor prefixes, is:

 -ms-word-break: break-all;
     word-break: break-all;

     /* Non standard for WebKit */
     word-break: break-word;

-webkit-hyphens: auto;
   -moz-hyphens: auto;
        hyphens: auto;

Using these properties on the universal selector can be useful if you have a site with a lot of user-generated content. Although fair warning, it can look weird on titles and pre-formatted text (

).
  • overflow-wrap
  • hyphens
  • white-space
  • Handling Long Words and URLs

Browser Support

Desktop

Chrome Firefox IE Edge Safari
23 49 11 18 6.1

Mobile / Tablet

Android Chrome Android Firefox Android iOS Safari
111 110 4.4 7.0-7.1

Safari and iOS support the break-all value but not keep-all

The web consists of content, content consists of words and words can be long, very long. Everyone involved with the web will sooner or later have to deal with long words.

Rindfleischetikettierungsüberwachungsaufgabenübertragungsgesetz

Demo

Browsing the web on my mobile device daily I see all kind of “failures” with long words – broken layouts, cropped words and situations like the one in the image above.

Hyphens #

The first solution for long words is using hyphens.

Demo

.hyphens {
-webkit-hyphens: auto;
-moz-hyphens: auto;
-ms-hyphens: auto;
hyphens: auto;
}

Browser support: CSS Hyphenation is supported in every major browser, except from all blink-based browsers (Chrome, Opera, Android) – Chromium bug. I also tested Safari 5.1 for Windows where hyphens are added but in my test words they were all on the wrong position and made no sense.

Furthermore, hyphens is language-sensitive. You have to define the lang attribute on the parent element and you should be aware that non-english languages are not supported very well across browsers.

You could also use a JavaScript library like Hyphenator.js which works with many languages and in lots of browsers. The downside is that you have to load a lot of extra JavaScript and especially for longer text it will hurt the performance.

word-break #

As browser support for hyphens isn’t really good, let’s try word-break – a CSS property to specify whether to break lines within words.

Demo

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

Browser support: CSS word-break is supported in every browser, except from Opera Mini and old presto-based Opera browsers. I also found some bugs when using word-break in combination with hyphens – more on that later.

Overflow-wrap #

The next solution is using word-wrap (overflow-wrap), another property to specify whether or not the browser may break lines within words.

Demo

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

Browser support: CSS overflow-wrap is supported in every (at least all I tested and listed on Can I use) browser. Note: Some browsers require the legacy name “word-wrap” (rather than “overflow-wrap”) to work.

Ellipsis #

Another option to handle long words is truncating.

Demo

.ellipsis {
overflow:hidden;
white-space: nowrap;
text-overflow: ellipsis;
}

Browser support: Text-overflow is supported in every major browser.

While this technique sounds like a good fit at a first glance it comes with disadvantages. First of all it will truncate every text after one line even if you use short words which would fit perfectly and would break in more lines. Furthermore, words could be truncated in a way that the original word will get another meaning – which may be funny at best or offensive at worst.

Please, don’t use text-overflow: ellipsis at all – truncating is not a job for CSS. If you really need it do it on the server side and only truncate after full words.

Conclusion #

I tested all the examples above and combinations of them in IE7, IE8, IE9, IE10, IE11, Edge, Firefox 39 (Windows, Linux, Mac), Chrome 44 (Windows, Linux, Mac), Opera 30 (Windows, Mac), Safari 8 (Mac), Safari 5.1 (Windows), Android 5 (Nexus 6), Android 4.4 (Nexus 5), Android 2.3 (Galaxy S2), iOS 8.3 (iPhone 6), iOS 7 (iPhone 5S), iOS 6 (iPhone5), Opera Mini (Android 5), Opera Classic (Android 5), Opera Mobile (Android 5) and Windows Phone 8.1 (Lumia 930) using real devices and BrowserStack – Here is a list of all 26 browsers and their results.

When searching the web you probably will find the following solution:

.hyphenate {
-ms-word-break: break-all;
word-break: break-all;
word-break: break-word;

-webkit-hyphens: auto;
-moz-hyphens: auto;
hyphens: auto;
}

While this works great in most cases, I found out that in Firefox hyphens won’t work (altough supported) in combination with word-break. Also, as word-break is not supported in Opera Mini it won’t work there.

As browser support for overflow-wrap is fantastic I tested the following, using overflow-wrap and hyphens:

Final solution #

.hyphenate {
overflow-wrap: break-word;
word-wrap: break-word;
-webkit-hyphens: auto;
-ms-hyphens: auto;
-moz-hyphens: auto;
hyphens: auto;
}

This solution will show hyphens for every browser supporting it and will break lines in every other browser – perfect. Altough I have tested this solution in 26 different browsers I am still not sure this will work 100% – if you find any edge case please let me know.

Update 28.09.2015
Some people asked why I didn’t mention HTML soft hyphens. There are two reasons. First of all, this post is about solutions using CSS and not HTML and second and more important is that I think it’s impractical to define possible hyphens in the text itself and almost impossible for editors to do that by hand.

Понравилась статья? Поделить с друзьями:
  • Break word with dash css
  • Break word not work
  • Break word in input
  • Break time one word or two
  • Break the word game