如何在 HTML 中实现文字自动换行?

210

如何将超出一个 div(比如 200px)宽度的文本像 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 进行自动换行?

我接受任何形式的解决方案,例如 CSS、jQuery 等。

21个回答

1
在HTML的body中尝试:


<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>

在CSS中尝试以下代码:

body

background-size: auto;

table-layout: fixed;

1
来自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;
}

更多的例子在这里


1
将此CSS添加到段落中。
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;

2
我和其他人一样喜欢text-overflow:ellipsis,但这并不是这个问题的正确答案。他想要换行而不是截断溢出部分。 - Spudley

0

我已经使用了Bootstrap。 我的HTML代码看起来像...

<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;
}

Bootstrap有text-justify类,因此您可以使用它来代替.wrap-text - barbsan

0

试试这个

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;
}

属性text-overflow: ellipsis可以在文本溢出时添加省略号,而line-clamp则用于显示行数。


0

你可以使用这个CSS

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

0

-1

试试这个

div {display: inline;}

-1
一个适合我使用的服务器端解决方案是:$message = wordwrap($message, 50, "<br>", true);,其中$message是包含要拆分的单词/字符的字符串变量。50是任何给定段落的最大长度,"<br>"是你想插入每个(50)字符的文本。

4
如果50倍字符宽度超过所需的最大值200像素,那么这个解决方案将不起作用。只需使用您的浏览器缩放功能,最终您会看到它会崩溃... - dokaspar

-1

尝试:

overflow-wrap: break-word;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接