Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

css - How to prevent long words from breaking my div?

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

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.

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

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").

Does anyone have a workable solution to this?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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})/ → $1­$2

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.

<wbr> element

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

averyvery<wbr>longword

Breaks with no hyphen:

averyvery
longword

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


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

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:table on other elements is fine. It will be as quirky (and stretchy) as old-school tables:

div.breaking {
   display: table-cell;
}

overflow and white-space: pre-wrap answers below are good too.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...