乐闻世界logo
搜索文章和话题

How to line-break from css, without using <br />?

1个答案

1

In CSS, if you want to break lines in text without using the <br/> tag, there are several effective methods to achieve this:

1. Using white-space and content Properties

To add a line break after specific content, utilize the ::after pseudo-element. For example:

html
<div class="wrap-text"> This is a long text repeated multiple times </div>
css
.wrap-text::after { content: '\A'; /* Unicode line break */ white-space: pre; /* Preserve whitespace handling to ensure the line break from \A takes effect */ }

This code inserts a line break after the content of .wrap-text.

2. Controlling Container Width

Force text to wrap by restricting the container's width. This approach requires no special CSS properties—simply set the container's width or max-width to make internal text wrap when it reaches the boundary. For example:

html
<div class="limited-width"> This is a long text repeated multiple times </div>
css
.limited-width { max-width: 200px; /* Limit maximum width */ }

This method controls wrapping via CSS, causing text to automatically wrap at the specified maximum width.

3. Using word-break or overflow-wrap

For text containing long words or URLs, employ word-break or overflow-wrap to ensure proper wrapping at boundaries. For example:

html
<div class="break-word"> This text contains a super long word: superlongwordthatneedstobreakproperly </div>
css
.break-word { word-break: break-all; }

The word-break: break-all; property ensures words break at any character, preventing overflow.

These methods offer flexibility in controlling CSS text wrapping without <br/>, enabling you to select the optimal approach based on your specific requirements.

2024年6月29日 12:07 回复

你的答案