What is the best way to break HTML text on slashes (/)?

无人久伴 提交于 2019-12-20 09:48:08

问题


I have an HTML table 360px wide, which works great. The challenge is that sometimes a url appears http://this/is/a/really-really-really-really-really/long/url in the text. This causes the table to expand horizontally and a scroll bar appears on the bottom.

I don't think overflow:hidden will work because half of the text would be hidden.

What is the best way to force breaking the line on slashes (/) and dashes (-) in CSS (hopefully)?

It should work with IE7+, Chrome, Firefox and Safari.

Working in Rails 3 and jQuery.


回答1:


You can use word-wrap : break-word; like so:

<div>http://www.aaa.com/bbb/ccc/ddd/eee/fff/ggg</div>

div {
    width : 50px;
    border : 1px solid #000;
    word-wrap : break-word;
}

I tested this in: I.E. 6/7/8, Firefox 7, Opera 11, Safari 5, Chrome 15

Here is a jsfiddle: http://jsfiddle.net/p4SxG/




回答2:


While the css word-wrap: break-word; does work, its implementation is different across browsers.

If you have control of the content and want exact breakpoints, you can insert

  • a <wbr> word break (supported in all major browsers except IE8 CanIUse.com);
  • &#8203; zero-width space (U+200B) - ugly in IE<=6
  • &shy; soft hyphen - though of course this adds a hyphen when breaking which is not always what is desired.

I have a large corporate user base who still have to use IE8, so when I hit this problem I used the C# someString.Replace("/", "/&#8203;") in the server-side code.

Gotcha: If you insert a zero-width space in an email address, when a user copies and pastes into their email client, the space gets copied too and the email will fail with no way for a user to see why (the space is zero width ...)

References

  • Stack Overflow
  • http://www.quirksmode.org/oddsandends/wbr.html - with examples

Further Reading

  • https://kenneth.io/blog/2012/03/04/word-wrapping-hypernation-using-css/ (March 2012)
  • https://css-tricks.com/almanac/properties/w/word-break/ (Sep 2012)
  • https://css-tricks.com/almanac/properties/h/hyphenate/ (Sep 2011)
  • https://developer.mozilla.org/en-US/docs/Web/CSS/word-break
  • https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-wrap


来源:https://stackoverflow.com/questions/8186743/what-is-the-best-way-to-break-html-text-on-slashes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!