Word and text wrap

Word for Microsoft 365 Word for the web Word 2021 Word 2019 Word 2016 Word 2013 More…Less

Moving or repositioning a picture on page in Word is as simple as dragging it with your mouse. But sometimes it doesn’t work. The key to getting the results you want is to select Layout Options.

Layout image button on a selected picture

  1. Select a picture.

  2. Select the Layout Options icon.

  3. Choose the layout options you want:

    Layout Options box

    • To bring your picture in front of the text and set it so it stays at a certain spot on the page, select In Front of Text (under With Text Wrapping), and then select Fix position on page.

    • To wrap text around the picture but have the picture move up or down as text is added or deleted, select Square (under With Text Wrapping), and then select Move with text.

For or more information and examples of text wrapping, see Wrap text around pictures in Word

The picture is probably behind another object, like a block of text:

Example of a picture behind a block of text

To select the picture, use the Selection pane:

  1. Select Home > Select > Selection Pane.

  2. In the Selection pane, select the picture.

To move a picture a tiny amount, select the picture, then hold down the Ctrl key and press an arrow key.

To move several objects at the same time, group them together:

  1. Select the first object.

  2. Hold down the Ctrl key and select the other objects.

  3. Right-click one of the objects, point to Group, and then select Group.

    Tip: If you are unable to group or multi-select pictures, it’s possible that the layout of your picture is inline with text. If so, please refer to Open Layout Options to change the picture layout to any option under With Text Wrapping.

For absolute control over the alignment and positioning of a picture, use the Layout box to set alignment relative to margins or columns, absolute position in inches, or relative position by percentage. This comes in handy when you want to place a picture a certain distance from something else, like a page margin.

  1. Select the picture.

  2. Select the Layout Options icon.

  3. Select See more, and then make alignment and position adjustments on the Position tab.

    If you can’t select any of the position options on the Position tab, select the Text Wrapping tab, and then select any option except the In line with text option.

If you have more than one picture that you want to overlap on a page, you can enable this in the Layout box.

  1. Select a picture.

  2. Select the Layout Options icon.

  3. Select See more.

  4. On the Position tab, in the Options group at the bottom, select the Allow overlap check box.

  5. Repeat for each picture for which you want to enable overlapping.

In addition to aligning and positioning pictures on a page, you can also align pictures to each other, or to other objects on the page. Although picture-to-picture alignment is not available from the Layout Options icon or the Layout dialog box, it’s a common task that you might do while working with picture positioning and alignment.

  1. Hold down the Ctrl key and select each object that you want to align.

  2. Go to Picture Format or Picture Tools Format > Align, and then choose an option, such as Center, Top, or Bottom.

An object anchor Object anchor icon indicates where a picture or object is located in relation to the text in your document. Anchors do not appear for inline pictures; inline objects are tied to the place within the text where they were inserted and are treated like any text character—»in line with text.»

All other wrapping options (Square, Tight, Through, Top and Bottom, Behind Text, In Front of Text) are anchored to a particular place in the document; the anchor indicates the paragraph with which the object is associated. Select a picture, and then select the Layout Options icon to find out how your picture is inserted.

Layout image button on a selected picture

Notes: If you select a picture and it’s not inline with text, but you don’t see an object anchor, you can ensure that anchors are shown in two ways:

  • Show formatting marks    On the Home tab, in the Paragraph group, select Show/Hide ¶.

  • Always show anchors    Select File > Options > Display, and then select Object anchors.

Because anchors are simply a visual indication of a picture’s relative position on a page, they cannot be removed. However, by trying different text wrapping options, you should find all the flexibility you need in positioning a picture, regardless of its anchor.

For or more information and examples of text wrapping, see Wrap text around pictures in Word.

If you want to ensure that an image stays put even if the text around it is deleted, you can lock its anchor:

  1. Select the picture.

  2. Select the Layout Options icon.

  3. Select See more, and then select Lock anchor.

    Note: Because anchors are not used for pictures placed In Line with Text, anchor locking and all other positioning options are unavailable for inline images.

See also

Wrap text around pictures in Word

Rotate a text box, shape, WordArt, or picture in Word

Group or ungroup shapes, pictures, or other objects

If you inserted a picture into your document while using Word for the web, you can cut and paste it to move it within a document, and you can apply paragraph formatting, like vertical spacing and centering, to it. However, you cannot move a picture that was inserted while using the desktop version of Word if the picture has text wrapping or a fixed position on the page.

If you find that you cannot make changes to a picture, and you have the desktop version of Word, select Open in Word to open your document in Word and make changes to its layout.

When you are done, press Ctrl+S to save your document to its original location. You can then open the document again in Word for the web, and continue editing. Word for the web will retain the layout settings that you applied in the desktop version of Word.

Need more help?

Want more options?

Explore subscription benefits, browse training courses, learn how to secure your device, and more.

Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.

Word’s Position and Wrap Text features help arrange images and text on the page. Position features automatically place the object at the location of your choice on the page (see how to position figures in Word for more details). Text Wrap features determine how text wraps around an image or other objects on the page, depending on the chosen option.

Wrap Text features work for figures in a Word document (see text wrapping for tables). Figures in Word mean any visual objects except tables and equations. So, using the same Wrap Text features can be used for images, ClipArt objects, charts, text boxes, diagrams, and SmartArt objects.

Change text wrapping

By default, Word inserts (see examples below):

  • Pictures (images and photos), charts in line with the text.
  • Text boxes, shapes in front of the text.
  • WordArt objects behind the text.

To change the way how text should wrap the object, select it, then do one of the following:

  • On the Picture Format (Shape Format, Graphics Format) tab, in the Arrange group, click the Wrap Text button:

    Wrap Text button in Word 365

  • Right-click on the object, then choose Wrap Text in the popup menu:

    Wrap Text of graphics in popup menu Word 365
      or  
    Wrap Text of shapes in popup menu Word 365

  • Click the Layout Options button that appears next to the selected figure:

    Layout Options button in Word 365

From the Wrap Text list, choose the option you prefer:

  • In Line with Text places an object in a paragraph on the same line as the surrounding text. The text does not wrap around it.

    Wrap Text - In Line with Text in Word 365

  • Square wraps the text around the picture or shape on all sides at right angles (a square pattern) as if it is rectangular. The text fills the remaining rectangular region.

    This option is the most common form of text wrapping.

    Wrap Text - Square in Word 365

  • Tight wraps the text around the edges of the figure. The text follows the shape.

    This option is most useful for larger images covering most of the page width.

    Wrap Text - Tight in Word 365

  • Through wraps the text around the picture or shape edges, including any white gaps. If there is no white space in the image or shape, text wrapping works the same as Tight.

    This option is an advanced setting because you pull or drag image and shape points in and out of their original borders:

    Wrap Text - Through in Word 365

    See how to edit hyphenation points.

  • Top and Bottom wraps the text above and below the figure to keep the image on its line. There is no text on either side of it.

    Wrap Text - Top and Bottom in Word 365

  • Behind Text places the figure behind, or underneath, any existing text. The text does not wrap around it.

    The picture looks like a watermark or background image.

    Wrap Text - Behind Text in Word 365

    Note: Use the Selection pane when working with objects behind the text.

  • In Front of Text places the object on top of the text. The text is not wrapped, so some of it may be blocked depending on the figure’s transparency.

    Wrap Text - In Front of Text in Word 365

Note: Figures that use the Square, Tight, Through, Top and Bottom, Behind Text, or In Front of Text wrapping style are all considered floating.

Position a figure to a paragraph or page

Also, Word offers two options for all wrapping styles except In line with Text (for floating figures):

Wrap Text options in popup menu Word 365
  or  
Layout Options button in Word 365

  • Move with Text moves the figure along with the surrounding text.

    If a figure is positioned inside the paragraph, and you delete or add any content before the paragraph, the figure moves with the paragraph. See more about Positioning a picture, text box, or shape on the page.

  • Fix Position on Page keeps the figure at the same place on the page when text is added or removed.

    If the paragraph where the figure is located (that paragraph contains anchor) moves to the next page, the figure moves and keeps its position relative to the page.

Note: The same options you can find in the Layout dialog box, on the Position tab, in the Options section:

Layout dialog box in Word 365

Checking the Move object with text check box is equivalent to the Move with Text option from the Wrap Text dropdown list. Unchecking the Move object with text check box is equivalent to the Fix Position on Page option.

Wrap text on both sides, or one side only

To change additional options, choose More Layout Options… from the Wrap Text dropdown list or the See more… link in the Layout Options menu.

In the Layout dialog box, on the Text Wrapping tab:

Text Wrapping tab in Layout dialog box Word 365

  • In the Wrapping style group, choose any style exact In line with text (see above).
  • In the Wrap text group (available for the Square, Tight, and Thought wrapping styles), choose any of the additional options:
    • Both sides wraps text around either side of the image or shape:

      Wrap Text - Both sides in Word 365

    • Left only wraps text around only the left side of the image or shape:

      Wrap Text - Left only in Word 365

    • Right only wraps text around only the right side of the image or shape:

      Wrap Text - Right only in Word 365

    • Largest only wraps text on the side of the image or shape with the larger distance from the margin.

Change the distance between text and object

To change the distance between text and the visual object, open the Layout dialog box by one of the following methods:

  • On the Picture Format (Shape Format, Graphics Format) tab, in the Arrange group, click the Wrap Text button, then select More Layout Options…
  • Right-click on the object, click the Wrap Text list, then select More Layout Options… in the popup menu.
  • Click the See more… link in the Layout Options menu.

In the Layout dialog box, on the Text Wrapping tab, in the Distance from text section, enter custom values for the distance between the text and the picture independently for:

  • Top and Bottom (available for the Square, Tight, Thought, and Top and Bottom wrapping styles),
  • Left and Right (available for the Square, Tight, and Thought wrapping styles).

For example, with the 0.3-inch distance on all sides:

Wrap Text - Distance from text in Word 365

Edit hyphenation points

To use the Tight or Through options effectively, you may need to adjust the wrapping points for the image or shape. To edit wrap points, select the object, then activate the Edit Wrap Points view by one of the following methods:

  • Picture Format (Shape Format, Graphics Format) tab, in the Arrange group, click the Wrap Text button. Then choose Edit Wrap Points from the Wrap Text dropdown list:

    Wrap Text - Edit Wrap Points in Word 365

  • Right-click on the object and select Wrap Text -> Edit Wrap Points in the popup menu:

    Edit Wrap Points in popup menu Word 365

In the Edit Wrap Points view, drag the red lines to adjust where the text wraps:

Edit Wrap Points in Word 365

Note: There is no way to add points. You can move existing wrap points however you want.

Be careful! After changing a text wrapping option or copy-pasting the picture, Word lost the changes of Wrap Points.


Download Article


Download Article

  • Adding an Image
  • |

  • Wrapping Text
  • |

  • Removing Wrap Text
  • |

  • Video
  • |

  • Q&A
  • |

  • Things You’ll Need

Microsoft Word helps you incorporate images and text together in order to illustrate a document, and you can learn to wrap text around images in order to change the default settings. This wikiHow shows you how to use wrap text in Word to add captions to images.

  1. Image titled Wrap Text in Word Step 1

    1

    Click on the area where you want your image. Once you do, a flashing vertical line appears right where you want the image placed.

    • A mouse is useful for working with images in Word, because you have more control of the size and shape when you can click and drag the image.
  2. Image titled Wrap Text in Word Step 2

    2

    Click Insert. This appears in the menu at the top of the page and pulls up a menu of different options.

    Advertisement

  3. Image titled Wrap Text in Word Step 3

    3

    Select Pictures.This will allow you to insert any jpg, pdf or other type of image that you have on your computer (or drives) into the document.

  4. Image titled Wrap Text in Word Step 4

    4

    Select Photo Browser. This will let you choose from the photo program on your computer.

    • Choose Picture From File if your image is on your desktop or in another folder.[1]
  5. Image titled Wrap Text in Word Step 5

    5

    Select your image. Once you’ve opened the dialog box for inserting an image, navigate to the folder where your image is saved and click on it once to select it for insertion into the document.

  6. Image titled Wrap Text in Word Step 6

    6

    Click Insert. This appears as a button at the bottom of the dialog box. Once done, your image is in the location you selected with your cursor.

  7. Image titled Wrap Text in Word Step 7

    7

    View your image. Keep in mind that Word’s default setting is to put the image “in line.” This means it will treat it as if it is a large letter or a tall line of text.

    • Text wrapping will allow the text to wrap around the image, go over the image or beside the image.
  8. Advertisement

  1. Image titled Wrap Text in Word Step 8

    1

    Click on the picture with your cursor. This action will bring up the Picture Formatting menu in the ribbon at the top of Word.

    • Clicking outside of the image will take the picture formatting menu away and bring you back to the text formatting menu.[2]
  2. Image titled Wrap Text in Word Step 9

    2

    Select Wrap Text. It may be inside the Arrange grouping or in the Advanced Layout tab, Drawing Tools tab or SmartArt Tools tab, depending on the version of Word you are running.

  3. Image titled Wrap Text in Word Step 10

    3

    Click the Wrap Text button. This appears in the top-right corner of your image when you click on it and will pull up a drop-down menu listing different text wrapping options.

  4. Image titled Wrap Text in Word Step 11

    4

    Select a text wrapping option. Word has different text wrapping options, which you can pick according to your needs:

    • Choose Square if your image is square and you want to wrap the text around the square border of your image.
    • Choose Top and Bottom if you want the image to stay on its own line, but be between text on the top and bottom.
    • Choose Tight to wrap text around a round or irregularly shaped image.
    • Choose Through to customize the areas that the text will wrap. This is best if you want the text to be incorporated with your image in some way, or not follow the borders of the image file. This is an advanced setting, because you will pull or drag image points in and out of their original borders.
    • Choose Behind Text to use the image as a watermark behind the text.
    • Choose In Front of Text to display the image over the text. You may want to change the color, or it can make the text illegible.
  5. Image titled Wrap Text in Word Step 12

    5

    Re-position the image. After you have selected your text wrapping option, you can click and drag your image to re-position it on the page. The program will allow you to place it where you want it now, with the text flowing around it.

  6. Image titled Wrap Text in Word Step 13

    6

    Experiment with different types of text wrapping. Each image and project requires different types of text wrapping. Browse through options when you add a new image to make sure your wrap text is properly formatted.

  7. Advertisement

  1. Image titled Wrap Text in Word Step 14

    1

    Click on the text box with your wrap text. This will pull up the markers for expanding and/or moving the text box along with making your text editable.

  2. Image titled Wrap Text in Word Step 15

    2

    Highlight all but the first letter of your wrap text. It’s important to leave the first letter un-highlighted because you’ll need to press the Backspace key, which could end up deleting the image you inserted above the wrap text.

  3. Image titled Wrap Text in Word Step 16

    3

    Press the Backspace key. This will delete the text you highlighted from the text box. Make sure to delete the first letter after the rest of the text, since this will reset your wrap text settings.

  4. Advertisement

Add New Question

  • Question

    I inserted a picture, chose «text wrapping,» and selected «tight.» How do I unwrap it?

    Community Answer

    Select the «In Line with Text» option in the same text wrapping menu. This will return the image to the default text wrapping setting — the same as when you initially added the image.

  • Question

    How do I get two images next to each other?

    Community Answer

    Just insert one picture right after the other (or put a space in-between if you want). If they don’t both fit on the same line, then resize them by clicking one of the corner squares and moving it inward.

  • Question

    How do I select which text will wrap around the picture?

    Community Answer

    Highlight the paragraph/words you would like to use and then select «Wrap text.»

Ask a Question

200 characters left

Include your email address to get a message when this question is answered.

Submit

Advertisement

Thanks for submitting a tip for review!

wikiHow Video: How to Wrap Text in Word

Things You’ll Need

  • Mouse
  • Microsoft Word

References

About This Article

Article SummaryX

«When you insert an object, such as an image or shape, into your Word document, you can choose how your text wraps around it. First, insert an object. To do this, click the place in your document where you’d like it to appear, click the «»Insert»» tab, and then select the object you want to include. By default, the object will be placed in line with the text, which means it’ll probably interrupt the document’s text flow. To make text wrap around the object instead, click the object once to select it, and then click the Layout Options icon at its top-right corner—it’s the half-circle surrounded by a bunch of lines. Now you’ll see several text-wrapping options under «»With Text Wrapping.»» Each option has an icon which illustrates how the text will wrap around the object. Click the first icon in this section to wrap the text around the object in a nice clean manner that adds a little space between the object and text. Or, click through the other options to see if they better suit your needs. If you drag the object to another location in the text, the text will continue to wrap around it using your selected text-wrapping setting. Click anywhere outside the object to close your Layout Options and return to editing your document.
»

Did this summary help you?

Thanks to all authors for creating a page that has been read 271,870 times.

Is this article up to date?

Text Wrapping in Microsoft Word

From corporate logos in press releases to scientific diagrams in research papers, there are many reasons to include images in a Microsoft Word document. But how images fit with surrounding text is important when formatting a document, so you need to understand text wrapping.

What Is Text Wrapping in Microsoft Word?

Text wrapping refers to how images are positioned in relation to text in a document, allowing you to control how pictures and charts are presented. Your options for this in Microsoft Word are:

In Line with Text

This option places an image on the same line as surrounding text. The image will thus move as text is added or removed, whereas the other options here mean the image stays in one position while text shifts and ‘wraps’ around it.

In-line text wrapping.

In-line text wrapping.
Square

This wraps text around an image on all sides at right angles, as if it had a rectangular box around it. This is the most common form of text wrapping.

Square wrapping.

Square wrapping.
Top and Bottom

Text wraps above and below the image so it is on its own line. This is most useful for larger images that occupy most of the width of a page.

Top and bottom wrapping.

Top and bottom wrapping.
Tight

This is similar to Square but without the rectangular box, so text wraps around the edges of the image itself. Useful for irregularly shaped images.

Tight text wrapping.

Tight text wrapping.
Through

Similar to Tight, but text will also fill any white gaps within the image.

Find this useful?

Subscribe to our newsletter and get writing tips from our editors straight to your inbox.

Text wrapping through an image.

Text wrapping through an image.
Behind

Places an image behind the text, allowing you to add a watermark or background image on a page (although MS Word has a separate watermark option, too, which is easier to use in many cases).

An image behind text.

An image behind text.
In Front of Text

Places the picture in front of the text. This can be used to place a circle around some text or to add an arrow to highlight part of a passage.

An image in front of text.

An image in front of text.

The best choice will depend on your needs, but Square and Tight work in most cases. As such, these should be your default options.

How to Control Text Wrapping

After adding an image to a document, you can adjust the text wrapping to make sure it fits with the surrounding text. To do this:

  • Click the image you want to format
  • Click Layout Options or go to Format > Arrange on the ribbon
  • Open the Wrap Text menu and select the setting required

Text wrapping options.

Text wrapping options.

If you want to use the Tight or Through options effectively, you may also need to adjust the wrapping points for the image. To do this:

  • Select the image you want to adjust
  • Go to Format > Arrange
  • Open the Wrap Text menu and click Edit Wrap Points
  • Drag the red lines to adjust the wrap points as required

Editing wrap points.

Editing wrap points.

The instructions above are for Microsoft Word on Windows computers, but the process is similar in Word for Mac.

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

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

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

Вы можете использовать свойства CSS word-wrap, overflow-wrap или word-break для обертывания или переноса слов, которые в противном случае переполнили бы их контейнер. Эта статья представляет собой подробное руководство по свойствам CSS word-wrap, overflow-wrap и word-break, а также о том, как вы можете использовать их, чтобы не допустить, чтобы переполнение содержимого разрушало ваш красиво оформленный макет.

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

Как происходит перенос контента в браузерах?

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

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

Хотя в английских текстах для символов пробела используются мягкие обертки, для неанглийских систем письма ситуация может быть иной. Некоторые языки не используют пробелов для разделения слов. Следовательно, упаковка содержимого зависит от языка или системы письма. Значение атрибута lang, которое вы указываете в элементе html, в основном используется для определения того, какая языковая система используется. В этой статье основное внимание будет уделено системе письма на английском языке.

Переноса по умолчанию при использовании мягкой обертки может быть недостаточно, если вы имеете дело с длинным непрерывным текстом, например URL-адресами или пользовательским контентом, который у вас недостаточно или совсем не контролируется.

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

В чем разница между мягким и принудительным переносом строки?

Любой перенос текста, который происходит при использовании мягкого переноса, называется разрывом мягкого переноса. Чтобы перенос происходил при использовании мягкого обертывания, необходимо убедиться, что обертывание включено. Например, установка значения nowrap для свойства white-space отключит перенос.

С другой стороны, принудительные разрывы строк возникают из-за явного управления разрывом строк или указания конца или начала блоков текста.

CSS свойства word-wrap и overflow-wrap

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

В последних версиях популярных веб-браузеров реализовано свойство overflow-wrap. В проекте спецификации CSS3 указано следующее определение overflow-wrap: Это свойство указывает, может ли браузер разбивать строку на недопустимые точки переноса, чтобы предотвратить переполнение, когда неразрывная строка слишком длинна, чтобы поместиться в границах контейнера.

Если у вас есть свойство white-space для элемента, вам необходимо установить для него значение allow, чтобы разрешить эффект переноса для overflow-wrap. Ниже приведены значения свойства overflow-wrap. Вы также можете использовать глобальные значения inherit, initial, revert и unset для overflow-wrap, но здесь мы не будем их рассматривать.

overflow-wrap: normal;

overflow-wrap: anywhere;

overflow-wrap: break-word;

Ниже мы рассмотрим значения свойства CSS overflow-wrap, чтобы понять его поведение.

Normal

Применение значения normal заставит браузер использовать поведение разрыва строки по умолчанию в системе. Поэтому для английского языка и других подобных системах письма разрывы строк будут происходить через пробелы и дефисы:

.my-element{

    overflow-wrap: normal;

}

На изображении ниже в тексте есть слово, длина которого превышает длину контейнера. Поскольку нет возможности мягкого переноса, а значение свойства overflow-wrap равно normal, слово переполняет свой контейнер. Это является поведением системы при переносе строк по умолчанию.

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

Anywhere

Использование значения в аnywhere приведет к разрыву неразрывной строки в произвольных точках между двумя символами. Аnywhere не будет добавлять символ дефиса, даже если вы примените свойство hyphens к этому элементу.
Браузер разорвет слово только в том случае, если отображение слова приведет к переполнению. Если слово вызывает переполнение, оно будет разорвано в точке, где это переполнение произошло.

Когда вы используете аnywhere, браузер будет учитывать возможности мягкого переноса, предоставляемые разрывом слова, при вычислении внутренних размеров min-content:

.my-element{

   overflow-wrap: anywhere;

}

В отличие от предыдущего примера, где мы использовали overflow-wrap: normal, на изображении ниже мы используем overflow-wrap :where. Слово-переполнение, которое невозможно разбить, разбивается на фрагменты текста с помощью overflow-wrap: anywhere, чтобы оно поместилось в своем контейнере.

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

Значение anywhere не поддерживается некоторыми браузерами. На изображении ниже показана поддержка браузерами по данным caniuse.com. Поэтому не рекомендуется использовать overflow-wrap: anywhere, если вы хотите иметь более высокую поддержку браузера.

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

Break-word

Значение break-word похоже на любое другое с точки зрения функциональности. Если браузер может перенести слово без переполнения, то он это сделает. Однако, если слово все еще переполняет контейнер, даже когда оно находится в новой строке, браузер разделит его в точке, где снова произошло бы переполнение:

.my-element{

   overflow-wrap: break-word;

}

На изображении ниже показано, как браузер прерывает переполненный текст в предыдущем разделе, когда вы применяете overflow-wrap: break-word. Вы заметите, что изображение ниже выглядит так же, как изображение в последнем примере. Разница между overflow-wrap: anywhere и overflow-wrap: break-word заключается в вычислении внутренних размеров min-content.

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

Разница между anywhere и break-word очевидна при вычислении внутренних размеров min-content. С break-word браузер не учитывает возможности мягкого переноса, предоставляемые разрывом слова, при вычислении внутренних размеров min-content, но он учитывает возможности мягкого переноса при использовании anywhere.

Значение break-word имеет достойный охват среди последних версий десктопных браузеров. К сожалению, этого нельзя сказать об их мобильном аналоге. Поэтому безопаснее использовать унаследованный word-wrap: break-word вместо более нового overflow-wrap: break-word.

На изображении ниже показана поддержка браузеров overflow-wrap: break-word согласно caniuse.com. Вы заметите, что последние версии десктопных браузеров имеют поддержку, в то время как поддержка некоторых мобильных браузеров неизвестна.

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

Свойство Word-break

Word-break — еще одно свойство CSS, которое вы можете использовать для указания возможности мягкого переноса между символами. Вы можете использовать это свойство, чтобы разбить слово в том месте, где могло произойти переполнение, и перенести его на следующую строку.

Ниже приводится то, что говорится о свойстве CSS word-break в спецификации CSS3:

Это свойство определяет возможности мягкого переноса между буквами, то есть там, где это «нормально» и допустимо для разрывов строк текста. Word-break контролирует, какие типы букв браузер может объединять в неразрывные «слова», заставляя символы CJK вести себя как текст, не относящийся к CJK, или наоборот.

Ниже приведены возможные значения CSS-свойства word-break. Как и для overflow-wrap, вы также можете использовать глобальные значения inherit, initial, revert и unset, но мы не будем рассматривать их здесь:

word-break: normal;

word-break: break-all;

word-break: keep-all;

Break-word также является значением для CSS-свойства word-break, хотя оно устарело. Однако, браузеры по-прежнему поддерживают его. Указание этого свойства имеет тот же эффект, что и word-break: normal и overflow-wrap :where.

Теперь, когда мы знакомы с CSS-свойством break-word и соответствующими ему значениями, давайте подробно рассмотрим их.

Normal

Установка для свойства word-break значение normal будет применять правила разбиения по словам по умолчанию:

.my-element{

   word-break: normal;

}

На изображении ниже показано, что происходит, когда вы применяете стиль word-break: normal к блоку текста, который содержит слово длиннее, чем его контейнер. Вы видите, что в браузере действуют обычные правила разбиения на слова.

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

Break-all

Значение break-all вставит разрыв строки именно в том месте, где текст переполнился бы для некитайских, неяпонских и некорейских систем письма. Слово не будет помещено в отдельную строку, даже если это предотвратит необходимость вставки разрыва строки:

.my-element{

   word-break: break-all;

}

На изображении ниже я применил стиль word-break:break-all к элементу p шириной 240 пикселей, содержащему переполненный текст. Браузер вставил разрыв строки в точке, где могло произойти переполнение, и перенес оставшийся текст в следующую строку.

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

Использование break-all приведет к разрыву слова между двумя символами именно в том месте, где произойдет переполнение в английском и других родственных языковых системах. Однако это не применимо к текстам на китайском, японском и корейском языках (CJK).

Он не применяет то же поведение к текстам CJK, потому что системы письма CJK имеют свои собственные правила для применения брейкпоинтов. Создание разрыва строки между двумя символами произвольно во избежание переполнения может значительно изменить общий смысл текста. Для систем CJK браузер будет применять разрывы строк в том месте, где такие разрывы разрешены.

На изображении ниже показана поддержка браузером word-break: break-word согласно caniuse.com. Хотя последние версии современных веб-браузеров поддерживают это значение, поддержка среди некоторых мобильных браузеров неизвестна.

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

Keep-all

Если вы используете значение keep-all, браузер не будет применять разрывы слов к текстам CJK, даже если происходит переполнение содержимого. Эффект от применения значения keep-all такой же, как и у normal для систем письма, отличных от CJK:

.my-element{

   word-break: keep-all;

}

На изображении ниже применение word-break: keep-all имеет тот же эффект, что и word-break: normal, потому что я использую систему письма, отличную от CJK (английский язык).

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

На изображении ниже показана поддержка браузером word-break: keep-all согласно caniuse.com. Это значение поддерживается в большинстве популярных десктопных браузеров. К сожалению, это не относится к мобильным браузерам.

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

Теперь, когда мы рассмотрели свойства CSS overflow-wrap и word-break, в чем разница между ними?

В чем разница между overflow-wrap и разр word-break?

Вы можете использовать CSS свойства overflow-wrap и word-break для управления переполнением содержимого. Однако существуют различия в способах обработки этих двух свойств.

Использование overflow-wrap приведет к переносу всего переполненного слова в новую строку, если оно может поместиться в одну строку, не переполняя свой контейнер. Браузер разорвет слово только в том случае, если он не сможет разместить слово в новой строке без переполнения. В большинстве случаев свойство overflow-wrap или его устаревшее название word-wrap может быть достаточным для управления переполнением содержимого.

Свойство overflow-wrap относительно новое, поэтому его поддержка браузером ограничена. Вместо этого вы можете использовать устаревшее название word-wrap, если вам нужна более высокая поддержка браузером.

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

Заключение

Как указывалось в предыдущих разделах, overflow-wrap и word-break во многом схожи. Вы можете использовать оба из них для управления разрывом строки.

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

Если вы хотите управлять переполнением содержимого, вам достаточно использовать overflow-wrap или его устаревшее название word-wrap.

Вы также можете использовать word-break, чтобы разбить слово между двумя символами, если слово выходит за пределы своего контейнера. Как и при overflow-wrap, при использовании word-break нужно действовать осторожно из-за ограничений в поддержке браузера.

Теперь, когда вы знаете поведение, связанное с этими двумя свойствами, вы можете решить, где и когда их использовать.

Автор: Joseph Mawa

Источник: blog.logrocket.com

Редакция: Команда webformyself.

Читайте нас в Telegram, VK, Яндекс.Дзен

Понравилась статья? Поделить с друзьями:
  • Word and text emotions
  • Word and term origins
  • Word and table of contents
  • Word and study tool
  • Word and string delphi