Html 如何防止长词破坏我的 div?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/320184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 22:48:03  来源:igfitidea点击:

How to prevent long words from breaking my div?

csslayouthtml

提问by Edward Tanguay

Ever since switching from TABLE-layout to DIV-layout, one common problem remains:

自从从 TABLE-layout 切换到 DIV-layout 之后,一个常见的问题仍然存在:

PROBLEM: you fill your DIV with dynamic text and inevitably there is a super-long word that extends over the edge of your div column and makes your site look unprofessional.

问题:你用动态文本填充你的 DIV,不可避免地会有一个超长的词延伸到你的 div 列的边缘,使你的网站看起来不专业。

RETRO-WHINING: This neverhappened with table layouts. A table cell will always nicely expand to the width of the longest word.

RETRO-WHINING:这在表格布局中从未发生过。表格单元格总是会很好地扩展到最长单词的宽度。

SEVERITY: I see this problem on even the most major sites, especially on German sites where even common words such as "speed limit" are very long ("Geschwindigkeitsbegrenzung").

严重性:我在大多数主要网站上都看到了这个问题,尤其是在德语网站上,即使是“限速”之类的常用词也很长(“Geschwindigkeitsbegrenzung”)。

Does anyone have a workable solution to this?

有没有人对此有可行的解决方案?

采纳答案by Kornel

Soft hyphen

软连字符

You can tell browsers where to split long words by inserting soft hyphen (­):

您可以通过插入软连字符 ( ­)来告诉浏览器在哪里拆分长单词:

averyvery­longword

may be rendered as

可以呈现为

averyverylongword

非常长的词

or

或者

averyvery-
longword

非常
长的词

A nice regular expression can ensure you won't be inserting them unless neccessary:

一个不错的正则表达式可以确保除非必要,否则您不会插入它们:

/([^\s-]{5})([^\s-]{5})/ → ­

Browsers and search engines are smart enough to ignore this character when searching text, and Chrome and Firefox (haven't tested others) ignore it when copying text to clipboard.

浏览器和搜索引擎足够聪明,可以在搜索文本时忽略此字符,而 Chrome 和 Firefox(尚未测试其他人)在将文本复制到剪贴板时会忽略它。

<wbr>element

<wbr>元素

Another option is to inject <wbr>, a former IE-ism, which is now in HTML5:

另一种选择是注入<wbr>一个以前的IE 主义,现在在 HTML5 中

averyvery<wbr>longword

Breaks with no hyphen:

不带连字符的中断:

averyvery
longword

非常
长的词

You can achieve the same with zero-width space character &#8203;(or &#x200B).

您可以使用零宽度空格字符&#8203;(或&#x200B)来实现相同的效果。



FYI there's also CSS hyphens: autosupported by latest IE, Firefox and Safari (but currently not Chrome):

仅供参考,最新的 IE、Firefox 和 Safari(但目前不支持 Chrome)也支持CSShyphens: auto

div.breaking {
  hyphens: auto;
}

However that hyphenation is based on a hyphenation dictionary and it's not guaranteed to break long words. It can make justified text prettier though.

然而,断字是基于断字字典的,它不能保证打破长词。不过,它可以使合理的文本更漂亮。

Retro-whining solution

复古抱怨解决方案

<table>for layout is bad, but display:tableon other elements is fine. It will be as quirky (and stretchy) as old-school tables:

<table>for 布局不好,但display:table在其他元素上很好。它将像老式桌子一样古怪(和弹性):

div.breaking {
   display: table-cell;
}


overflowand white-space: pre-wrapanswers below are good too.

overflowwhite-space: pre-wrap下面的答案也很好。

回答by Oli

Two fixes:

两个修复:

  1. overflow:scroll-- this makes sure your content can be seen at the cost of design (scrollbars are ugly)
  2. overflow:hidden-- just cuts off any overflow. It means people can't read the content though.
  1. overflow:scroll-- 这确保您的内容可以以设计为代价被看到(滚动条很难看)
  2. overflow:hidden- 只是切断任何溢出。这意味着人们无法阅读内容。

If (in the SO example) you want to stop it overlapping the padding, you'd probably have to create another div, inside the padding, to hold your content.

如果(在 SO 示例中)您想阻止它与填充重叠,您可能必须在填充内创建另一个 div 来保存您的内容。

Edit: As the other answers state, there are a variety of methods for truncating the words, be that working out the render width on the client side (never attempt to do this server-side as it will never work reliably, cross platform) through JS and inserting break-characters, or using non-standard and/or wildly incompatible CSS tags (word-wrap: break-worddoesn't appear to work in Firefox).

编辑:正如其他答案所述,有多种截断单词的方法,即在客户端计算渲染宽度(切勿尝试在服务器端执行此操作,因为它永远不会可靠地跨平台工作)通过JS 并插入中断字符,或使用非标准和/或非常不兼容的 CSS 标签(word-wrap: break-word在 Firefox 中似乎不起作用)。

You will always need an overflow descriptor though. If your div contains another too-wide block-type piece of content (image, table, etc), you'll need overflow to make it not destroy the layout/design.

不过,您将始终需要一个溢出描述符。如果您的 div 包含另一个太宽的块类型内容(图像、表格等),您将需要溢出以使其不会破坏布局/设计。

So by all means use another method (or a combination of them) but remember to add overflow too so you cover all browsers.

所以一定要使用另一种方法(或它们的组合),但记住也要添加溢出,以便覆盖所有浏览器。

Edit 2 (to address your comment below):

编辑 2(以解决您在下面的评论):

Start off using the CSS overflowproperty isn't perfect but it stops designs breaking. Apply overflow:hiddenfirst. Remember that overflow might not break on padding so either nest divs or use a border (whatever works best for you).

开始使用 CSSoverflow属性并不完美,但它可以阻止设计中断。overflow:hidden先申请。请记住,溢出可能不会在填充时中断,因此可以使用 nestdiv或使用边框(无论哪种方式最适合您)。

This will hide overflowing content and therefore you might lose meaning. You could use a scrollbar (using overflow:autoor overflow:scrollinstead of overflow:hidden) but depending on the dimensions of the div, and your design, this might not look or work great.

这将隐藏溢出的内容,因此您可能会失去意义。您可以使用滚动条(使用overflow:autooverflow:scroll代替overflow:hidden),但根据 div 的尺寸和您的设计,这可能看起来或效果不佳。

To fix it, we can use JS to pull things back and do some form of automated truncation. I was half-way through writing out some pseudo code for you but it gets seriously complicated about half-way through. If you need to show as much as possible, give hyphenatora look in (as mentioned below).

为了修复它,我们可以使用 JS 将事情拉回来并进行某种形式的自动截断。我已经为你写了一些伪代码,但在中途它变得非常复杂。如果您需要尽可能多地显示,请查看连字符如下所述)。

Just be aware that this comes at the cost of user's CPUs. It could result in pages taking a long time to load and/or resize.

请注意,这是以用户的 CPU 为代价的。这可能导致页面加载和/或调整大小需要很长时间。

回答by Neil Monroe

This is a complex issue, as we know, and not supported in any common way between browsers. Most browsers don't support this feature natively at all.

正如我们所知,这是一个复杂的问题,并且在浏览器之间不受任何常见方式的支持。大多数浏览器本身根本不支持此功能。

In some work done with HTML emails, where user content was being used, but script is not available (and even CSS is not supported very well) the following bit of CSS in a wrapper around your unspaced content block should at least help somewhat:

在一些使用 HTML 电子邮件完成的工作中,其中使用了用户内容,但脚本不可用(甚至对 CSS 的支持也不是很好),围绕未间隔内容块的包装器中的以下 CSS 位至少应该有所帮助:

.word-break {
  /* The following styles prevent unbroken strings from breaking the layout */
  width: 300px; /* set to whatever width you need */
  overflow: auto;
  white-space: -moz-pre-wrap; /* Mozilla */
  white-space: -hp-pre-wrap; /* HP printers */
  white-space: -o-pre-wrap; /* Opera 7 */
  white-space: -pre-wrap; /* Opera 4-6 */
  white-space: pre-wrap; /* CSS 2.1 */
  white-space: pre-line; /* CSS 3 (and 2.1 as well, actually) */
  word-wrap: break-word; /* IE */
  -moz-binding: url('xbl.xml#wordwrap'); /* Firefox (using XBL) */
}

In the case of Mozilla-based browsers, the XBL file mentioned above contains:

对于基于 Mozilla 的浏览器,上面提到的 XBL 文件包含:

<?xml version="1.0" encoding="utf-8"?>
<bindings xmlns="http://www.mozilla.org/xbl" 
          xmlns:html="http://www.w3.org/1999/xhtml">
  <!--
  More information on XBL:
  http://developer.mozilla.org/en/docs/XBL:XBL_1.0_Reference

  Example of implementing the CSS 'word-wrap' feature:
  http://blog.stchur.com/2007/02/22/emulating-css-word-wrap-for-mozillafirefox/
  -->
  <binding id="wordwrap" applyauthorstyles="false">
    <implementation>
      <constructor>
        //<![CDATA[
        var elem = this;

        doWrap();
        elem.addEventListener('overflow', doWrap, false);

        function doWrap() {
          var walker = document.createTreeWalker(elem, NodeFilter.SHOW_TEXT, null, false);
          while (walker.nextNode()) {
            var node = walker.currentNode;
            node.nodeValue = node.nodeValue.split('').join(String.fromCharCode('8203'));
          }
        }
        //]]>
      </constructor>
    </implementation>
  </binding>
</bindings>

Unfortunately, Opera 8+ don't seem to like any of the above solutions, so JavaScript will have to be the solution for those browsers (like Mozilla/Firefox.) Another cross-browser solution (JavaScript) that includes the later editions of Opera would be to use Hedger Wang's script found here: http://www.hedgerwow.com/360/dhtml/css-word-break.html

不幸的是,Opera 8+ 似乎不喜欢上述任何解决方案,因此 JavaScript 将不得不成为这些浏览器(如 Mozilla/Firefox)的解决方案。另一种跨浏览器解决方案 (JavaScript),包括更高版本的 Opera将使用在这里找到的 Hedger Wang 的脚本:http: //www.hedgerwow.com/360/dhtml/css-word-break.html

Other useful links/thoughts:

其他有用的链接/想法:

Incoherent Babble ? Blog Archive ? Emulating CSS word-wrap for Mozilla/Firefox
http://blog.stchur.com/2007/02/22/emulating-css-word-wrap-for-mozillafirefox/

语无伦次的胡言乱语?博客存档?为 Mozilla/Firefox 模拟 CSS 自动换行
http://blog.stchur.com/2007/02/22/emulating-css-word-wrap-for-mozillafirefox/

[OU] No word wrap in Opera, displays fine in IE
http://list.opera.com/pipermail/opera-users/2004-November/024467.html
http://list.opera.com/pipermail/opera-users/2004-November/024468.html

[OU] 在 Opera 中没有自动换行,在 IE 中显示正常
http://list.opera.com/pipermail/opera-users/2004-November/024467.html
http://list.opera.com/pipermail/opera-用户/2004-11 月/024468.html

回答by Remo

CSS Cross Browser Word Wrap

CSS 跨浏览器自动换行

.word_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+ */
}

回答by sanimalp

Use the style word-break:break-all;. I know it works on tables.

使用样式word-break:break-all;。我知道它适用于桌子。

回答by VonC

Do you mean that, in browsers that support it, word-wrap: break-worddoes not work ?

你的意思是,在支持它的浏览器中,word-wrap: break-word不起作用?

If included in the body definition of the stylesheet, it should works throughout the entire document.

如果包含在 stylesheet 的 body 定义中,它应该适用于整个文档。

If overflow is not a good solution, only a custom javascript could artificially break up long word.

如果溢出不是一个好的解决方案,只有自定义 javascript 才能人为地分解长字。

Note: there is also this <wbr>Word Break tag. This gives the browser a spot where it can split the line up. Unfortunately, the <wbr>tag doesn't work in all browsers, only Firefox and Internet Explorer (and Opera with a CSS trick).

注意:还有这个<wbr>Word Break 标签。这为浏览器提供了一个可以拆分行的位置。不幸的是,该<wbr>标签不适用于所有浏览器,只有 Firefox 和 Internet Explorer(以及带有 CSS 技巧的 Opera)。

回答by Zac Imboden

Just checked IE 7, Firefox 3.6.8 Mac, Firefox 3.6.8 Windows, and Safari:

刚刚检查了 IE 7、Firefox 3.6.8 Mac、Firefox 3.6.8 Windows 和 Safari:

word-wrap: break-word;

works for long links inside of a div with a set width and no overflow declared in the css:

适用于具有设置宽度且在 css 中未声明溢出的 div 内的长链接:

#consumeralerts_leftcol{
    float:left;
    width: 250px;
    margin-bottom:10px;
    word-wrap: break-word;
}

I don't see any incompatibility issues

我没有看到任何不兼容问题

回答by dylanfm

I just found out about hyphenatorfrom this question. That might solve the problem.

我刚刚从这个问题中发现了关于连字符的信息。那可能会解决问题。

回答by mpen

After much fighting, this is what worked for me:

经过多次战斗,这对我有用:

.pre {
    font-weight: 500;
    font-family: Courier New, monospace;
    white-space: pre-wrap;
    word-wrap: break-word;
    word-break: break-all;
    -webkit-hyphens: auto;
    -moz-hyphens: auto;
    hyphens: auto;
}

Works in the latest versions of Chrome, Firefox and Opera.

适用于最新版本的 Chrome、Firefox 和 Opera。

Note that I excluded many of the white-spaceproperties the others suggested -- that actually broke the preindentation for me.

请注意,我排除white-space了其他人建议的许多属性——这实际上破坏了pre我的缩进。

回答by Jacob

For me on a div without fixed size and with dynamic content it worked using:

对于我在没有固定大小和动态内容的 div 上,它使用:

display:table;
word-break:break-all;