好吧,这真把我搞糊涂了。我在一个div里面有一些内容,就像这样:

<div style="background-color: green; width: 200px; height: 300px;">

Thisisatest.Thisisatest.Thisisatest.Thisisatest.Thisisatest.Thisisatest.

</div>

但是,由于“word”太长,内容会溢出DIV(正如预期的那样)。

我怎么能迫使浏览器在必要的地方“打破”这个词,以适应里面的所有内容?


当前回答

这可以添加到“跨浏览器”解决方案的可接受答案中。

来源:

http://kenneth.io/blog/2012/03/04/word-wrapping-hypernation-using-css/ http://css-tricks.com/snippets/css/prevent-long-urls-from-breaking-out-of-container/

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

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

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

其他回答

当使用flexbox并依赖于宽度时,发现使用以下功能在大多数主流浏览器(Chrome, IE, Safari iOS/OSX)上都有效,除了Firefox (v50.0.2):

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

注意:如果你不使用自动修复器,你可能需要添加浏览器厂商前缀。

另一件需要注意的事情是使用&nbsp;因为空格会在中间导致换行。

首先,您应该确定元素的宽度。例句:

# sampleDiv { 宽度:80%; 自动换行:break-word; } < div id = " sampleDiv " > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa < / div >

因此,当文本达到元素宽度时,它将被分解成行。

我用下面的代码解决了这个问题。

display: table-caption;

为此,您可以使用网格系统。

<div class="container" style="background-color: green; width: 200px; height: 300px;">
   <div class="row">Thisisatest.Thisisatest.Thisisatest.</div>
   <div class="row">Thisisatest.Thisisatest.Thisisatest.</div>
 </div>

空白由浏览器保留。文本将在必要时自动换行,并在换行时自动换行

.pre-wrap {
    white-space: pre-wrap;
    word-break: break-word;
}

DEMO

td { 单词分割:break-word; 空白:pre-wrap; -moz-white-space: pre-wrap; } 表{ 宽度:100 px; 边框:1px纯黑色; 显示:块; } <表> < tr > < th > < / th >列表 < td > 1. longtextlongtextlongtextlongtextlongtextlongtextlongtextlongtextlongtextlongtextlongtextlongtext 2. breaklinebreaklinebreaklinebreaklinebreaklinebreaklinebreaklinebreaklinebreaklinebreaklinebreakline < / td > < / tr > 表> < /