Inline style word wrap

How can text like aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa which exceeds the width of a div (say 200px) be wrapped?

I am open to any kind of solution such as CSS, jQuery, etc.

trejder's user avatar

trejder

17k27 gold badges123 silver badges215 bronze badges

asked Jul 18, 2009 at 15:56

Satya Kalluri's user avatar

Satya KalluriSatya Kalluri

5,1084 gold badges27 silver badges37 bronze badges

Try this:

div {
    width: 200px;
    word-wrap: break-word;
}

answered Jul 18, 2009 at 16:02

Alan Haggai Alavi's user avatar

Alan Haggai AlaviAlan Haggai Alavi

72.2k19 gold badges101 silver badges127 bronze badges

6

On bootstrap 3, make sure the white-space is not set as ‘nowrap’.

div {
  width: 200px;
  word-break: break-all;
  white-space: normal;
}

answered Nov 12, 2013 at 8:39

lukaserat's user avatar

2

You can use a soft hyphen like so:

aaaaaaaaaaaaaaa­aaaaaaaaaaaaaaa

This will appear as

aaaaaaaaaaaaaaa-
aaaaaaaaaaaaaaa

if the containing box isn’t big enough, or as

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

if it is.

Tunaki's user avatar

Tunaki

131k46 gold badges330 silver badges415 bronze badges

answered Jul 18, 2009 at 16:13

Kim Stebel's user avatar

Kim StebelKim Stebel

41.6k12 gold badges125 silver badges142 bronze badges

7

div {
    /* Set a width for element */
    word-wrap: break-word
}

The ‘word-wrap‘ solution only works in IE and browsers supporting CSS3.

The best cross browser solution is to use your server side language (php or whatever) to locate long strings and place inside them in regular intervals the html entity
This entity breaks the long words nicely, and works on all browsers.

e.g.

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa​aaaaaaaaaaaaaaaaaaaaaaaaaaaaa

code's user avatar

code

5,1204 gold badges16 silver badges37 bronze badges

answered Jul 18, 2009 at 16:14

Orr Siloni's user avatar

Orr SiloniOrr Siloni

1,24010 silver badges20 bronze badges

1

This worked for me

word-wrap: normal;
word-break: break-all;
white-space: normal;
display: block;
height: auto;
margin: 3px auto;
line-height: 1.4;
-webkit-line-clamp: 1;
-webkit-box-orient: vertical;

answered Jun 2, 2016 at 2:04

Amol's user avatar

AmolAmol

9087 silver badges20 bronze badges

1

The only one that works across IE, Firefox, chrome, safari and opera if there are no spaces in the word (such as a long URL) is:

div{
    width: 200px;  
    word-break: break-all;
}

I found this to be bullet-proof.

Radek Postołowicz's user avatar

answered Apr 12, 2013 at 13:56

Kyle Dearle's user avatar

Kyle DearleKyle Dearle

1291 gold badge2 silver badges9 bronze badges

0

Another option is also using:

div
{
   white-space: pre-line;
}

This will set all your div elements in all browsers that support CSS1 (which is pretty much all common browsers as far back as IE 8)

answered Oct 14, 2014 at 15:59

Andrew Marais's user avatar

1

Cross Browser

.wrap
{
    white-space: pre-wrap; /* css-3 */    
    white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
    white-space: -pre-wrap; /* Opera 4-6 */    
    white-space: -o-pre-wrap; /* Opera 7 */    
    word-wrap: break-word; /* Internet Explorer 5.5+ */
}

Community's user avatar

answered Apr 20, 2015 at 9:21

Timeless's user avatar

TimelessTimeless

7,2898 gold badges60 silver badges94 bronze badges

<p style="word-wrap: break-word; word-break: break-all;">
    Adsdbjf bfsi hisfsifisfsifs shifhsifsifhis aifoweooweoweweof
</p>

answered Oct 1, 2020 at 20:23

Manoj Alwis's user avatar

Manoj AlwisManoj Alwis

1,27911 silver badges24 bronze badges

Example from CSS Tricks:

div {
    -ms-word-break: break-all;

    /* Be VERY careful with this, breaks normal words wh_erever */
    word-break: break-all;

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

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

More examples here.

answered Feb 4, 2015 at 10:01

Juraj Guniš's user avatar

In HTML body try:

<table>
    <tr>
        <td>
            <div style="word-wrap: break-word; width: 800px">
                Hello world, how are you? More text here to see if it wraps after a long while of writing and it does on Firefox but I have not tested it on Chrome yet. It also works wonders if you have a medium to long paragraph. Just avoid writing in the CSS file that the words have to break-all, that's a small tip.
            </div>
        </td>
    </tr>
</table>

In CSS body try:

background-size: auto;

table-layout: fixed;

John Slegers's user avatar

John Slegers

44.5k22 gold badges201 silver badges169 bronze badges

answered Feb 6, 2016 at 17:06

Wesson2's user avatar

Add this CSS to the paragraph.

width:420px; 
min-height:15px; 
height:auto!important; 
color:#666; 
padding: 1%; 
font-size: 14px; 
font-weight: normal;
word-wrap: break-word; 
text-align: left;

TylerH's user avatar

TylerH

20.6k64 gold badges76 silver badges97 bronze badges

answered May 23, 2012 at 9:53

Swapnil Godambe's user avatar

Swapnil GodambeSwapnil Godambe

2,0541 gold badge24 silver badges28 bronze badges

1

Try this

div{
  display: block;
  display: -webkit-box;
  height: 20px;
  margin: 3px auto;
  font-size: 14px;
  line-height: 1.4;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

the property text-overflow: ellipsis add … and line-clamp show the number of lines.

answered Nov 27, 2014 at 21:10

Vladimir Salguero's user avatar

I have used bootstrap.
My html code looks like ..

<div class="container mt-3" style="width: 100%;">
  <div class="row">
    <div class="col-sm-12 wrap-text">
      <h6>
        text content
      </h6>
    </div>
  </div>
</div>

CSS

.wrap-text {
     text-align:justify;
}

Stephen Rauch's user avatar

Stephen Rauch

47.2k31 gold badges110 silver badges133 bronze badges

answered Sep 18, 2018 at 2:24

Rahul Wasnik's user avatar

1

you can use this CSS

p {
  width: min-content;
  min-width: 100%;
}

answered Dec 27, 2019 at 10:22

Rashid Iqbal's user avatar

Rashid IqbalRashid Iqbal

1,05313 silver badges12 bronze badges

Try this CSS property —

overflow-wrap: anywhere;

answered Jun 9, 2022 at 6:12

Akshay Chavan's user avatar

A server side solution that works for me is: $message = wordwrap($message, 50, "<br>", true); where $message is a string variable containing the word/chars to be broken up. 50 is the max length of any given segment, and "<br>" is the text you want to be inserted every (50) chars.

answered Jan 23, 2012 at 7:31

deshbanks's user avatar

1

Try this

div {display: inline;}

answered Jul 18, 2018 at 16:58

Michael Mulikita's user avatar

try:

overflow-wrap: break-word;

borchvm's user avatar

borchvm

3,48411 gold badges45 silver badges43 bronze badges

answered Jan 29, 2020 at 3:00

Eden Sharvit's user avatar

Use word-wrap:break-word attribute along with required width. Mainly, put
the width in pixels, not in percentages.

width: 200px;
word-wrap: break-word;

JSuar's user avatar

JSuar

21.1k4 gold badges43 silver badges82 bronze badges

answered Jan 27, 2011 at 8:36

aks's user avatar

1

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

Example

Allow long words to be able to break and wrap onto the next line:

div {
  word-wrap: break-word;
}

Try it Yourself »


Definition and Usage

The word-wrap property allows long words to be able to be broken and wrap
onto the next line.

Show demo ❯

Default value: normal
Inherited: yes
Animatable: no. Read about animatable
Version: CSS3
JavaScript syntax: object.style.wordWrap=»break-word»
Try it

Browser Support

The numbers in the table specify the first browser version that fully supports the property.

Property
word-wrap 4.0 5.5 3.5 3.1 10.5

CSS Syntax

word-wrap: normal|break-word|initial|inherit;

Property Values

Value Description Demo
normal Break words only at allowed break points. This is default Demo ❯
break-word Allows unbreakable words to be broken Demo ❯
initial Sets this property to its default value. Read about initial
inherit Inherits this property from its parent element. Read about inherit

Related Pages

CSS tutorial: CSS Text Effects

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.

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

Краткая информация

Значение по умолчанию normal
Наследуется Да
Применяется Ко всем элементам
Процентная запись Неприменима
Анимируется Нет

Синтаксис

word-wrap: normal | break-word

Синтаксис

Описание Пример
<тип> Указывает тип значения. <размер>
A && B Значения должны выводиться в указанном порядке. <размер> && <цвет>
A | B Указывает, что надо выбрать только одно значение из предложенных (A или B). normal | small-caps
A || B Каждое значение может использоваться самостоятельно или совместно с другими в произвольном порядке. width || count
[ ] Группирует значения. [ crop || cross ]
* Повторять ноль или больше раз. [,<время>]*
+ Повторять один или больше раз. <число>+
? Указанный тип, слово или группа не является обязательным. inset?
{A, B} Повторять не менее A, но не более B раз. <радиус>{1,4}
# Повторять один или больше раз через запятую. <время>#

Значения

normal
Строки не переносятся или переносятся в тех местах, где явно задан перенос (например, с помощью <br>).
break-word
Перенос строк добавляется автоматически, чтобы слово поместилось в заданную ширину блока.

Пример

<!DOCTYPE html>
<html>
<head>
<meta charset=»utf-8″>
<title>word-wrap</title>
<style>
.col {
background: #f0f0f0; /* Цвет фона */
width: 230px; /* Ширина блока */
padding: 10px; /* Поля */
font-size: 1.5em; /* Размер шрифта */
word-wrap: break-word; /* Перенос слов */
}
</style>
</head>
<body>
<div class=»col»>
<p>Cуществительное</p>
<p>высокопревосходительство</p>
<p>Одушевленное существительное</p>
<p>одиннадцатиклассница</p>
<p>Химическое вещество</p>
<p>метоксихлордиэтиламинометилбутиламиноакридин</p>
</div>
</body>
</html>

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

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

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

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

Объект.style.wordWrap

Спецификация

Спецификация Статус
CSS Text Level 3 Рабочий проект

Спецификация

Каждая спецификация проходит несколько стадий одобрения.

  • Recommendation (Рекомендация) — спецификация одобрена W3C и рекомендована как стандарт.
  • Candidate Recommendation (Возможная рекомендация) — группа, отвечающая за стандарт, удовлетворена, как он соответствует своим целям, но требуется помощь сообщества разработчиков по реализации стандарта.
  • Proposed Recommendation (Предлагаемая рекомендация) — на этом этапе документ представлен на рассмотрение Консультативного совета W3C для окончательного утверждения.
  • Working Draft (Рабочий проект) — более зрелая версия черновика после обсуждения и внесения поправок для рассмотрения сообществом.
  • Editor’s draft (Редакторский черновик) — черновая версия стандарта после внесения правок редакторами проекта.
  • Draft (Черновик спецификации) — первая черновая версия стандарта.

Браузеры

5.5 12 1 10.5 1 3.5

Браузеры

В таблице браузеров применяются следующие обозначения.

  • — элемент полностью поддерживается браузером;
  • — элемент браузером не воспринимается и игнорируется;
  • — при работе возможно появление различных ошибок, либо элемент поддерживается с оговорками.

Число указывает версию браузреа, начиная с которой элемент поддерживается.

Понравилась статья? Поделить с друзьями:
  • Index lines in word
  • Ink в word онлайн конвертер
  • Insert function if excel
  • Initials forming a word
  • Index in word 2007