How to wrap long lines without spaces in HTML?

2019-01-08 11:49发布

问题:

If a user types in a long line without any spaces or white space, it will break formating by going wider than the current element. Something like:

HAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHA.............................................................................................................................................

I've tried just using wordwrap() in PHP, but the problem with that is if there is a link or some other valid HTML, it breaks.

There seems to be a few options in CSS, but none of them work in all browsers. See word-wrap in IE.

How do you solve this problem?

回答1:

I haven't personally used it, but Hyphenator looks promising.

Also see related (possibly duplicate) questions:

  • word wrap in css / js
  • Who has solved the long-word-breaks-my-div problem? (hint: not stackoverflow)


回答2:

in CSS3:

word-wrap:break-word


回答3:

I was trying to solve the same problem and I found de solution here:

http://perishablepress.com/press/2010/06/01/wrapping-content/

Solution: adding to the container the following CSS properties

div {
    white-space: pre;           /* CSS 2.0 */
    white-space: pre-wrap;      /* CSS 2.1 */
    white-space: pre-line;      /* CSS 3.0 */
    white-space: -pre-wrap;     /* Opera 4-6 */
    white-space: -o-pre-wrap;   /* Opera 7 */
    white-space: -moz-pre-wrap; /* Mozilla */
    white-space: -hp-pre-wrap;  /* HP Printers */
    word-wrap: break-word;      /* IE 5+ */
}

The idea is using them all so you get better cross-browser compatibility

Hope this helps



回答4:

I like to use the overflow: auto CSS property/value pairing. This will render the parent object the way you'd expect it to appear. If the text within the parent is too wide, scrollbars appear within the object itself. This will keep the structure the way you want it to look and provide the viewer with the ability to scroll over to see more.

Edit: the nice thing about overflow: auto compared to overflow: scroll is that with auto, the scrollbars will only appear when overflowing content exists. With scroll, the scrollbars are always visible.



回答5:

I'm surprised that nobody has mentioned one of my favorite solutions to this problem, the <wbr> (optional line-break) tag. It's fairly well-supported in browsers and essentially tells the browser that it can insert a line-break if it's necessary. There's also the related zero-width space character, &#8203; with the same meaning.

For the use case mentioned, displaying user comments on a web page, I would assume that there is already some output formatting to prevent injection attacks, etc. So it's simple to add these <wbr> tags every N characters in words that are too long, or in links.

This is especially useful when you need control over the format of the output, which CSS doesn't always let you do.



回答6:

I would put the post in a div that would have a fixed width setting overflow to scroll (or to hide completely depending on the content).

so like:

#post{
    width: 500px;
    overflow: scroll;
}

But that's just me.

EDIT: As cLFlaVA points out... it is better to use auto then scroll. I do agree with him.



回答7:

There is no "perfect" HTML/CSS solution.

The solutions either hide the overflow (ie scrolling or just hidden) or expand to fit. There is no magic.

Q: How can you fit a 100cm wide object into a space only 99cm wide?

A: You can't.

You can read break-word

EDIT

Please check out this solution How to apply a line wrap/continuation style and code formatting with css

or

How to prevent long words from breaking my div?



回答8:

I dodge the problem by not having my right sidebar fixed like that :P



回答9:

Here's what I do in ASP.NET:

  1. Split the text field on spaces to get all the words
  2. Iterate the words looking for words that are longer than a certain amount
  3. Insert every x characters (e.g. every 25 characters.)

I looked at other CSS based ways of doing this, but didn't find anything that worked cross-browser.



回答10:

based on Jon's suggestion the code that I created:

public static string WrapWords(string text, int maxLength)
    {
        string[] words = text.Split(' ');
        for (int i = 0; i < words.Length; i++)
        {
            if (words[i].Length > maxLength) //long word
            {
                words[i] = words[i].Insert(maxLength, " ");
                //still long ?
                words[i]=WrapWords(words[i], maxLength);
            }
        }
        text = string.Join(" ", words);
        return (text);
    }


回答11:

I didn't want to add libraries to my pages just for word breaking. Then I wrote a simple function which I provide below, hope it helps people.

(It is breaking by 15 characters, and applying "& shy;" between, but you can change it easily in the code)

//the function:
BreakLargeWords = function (str)
{
    BreakLargeWord = function (word)
    {
        var brokenWords = [];
        var wpatt = /\w{15}|\w/igm;
        while (wmatch = wpatt.exec(word))
        {
            var brokenWord = wmatch[0];
            brokenWords.push(brokenWord);
            if (brokenWord.length >= 15) brokenWords.push("&shy;");
        }
        return brokenWords.join("");
    }

    var match;
    var word = "";
    var words = [];
    var patt = /\W/igm;
    var prevPos = 0;
    while (match = patt.exec(str))
    {
        var pos = match.index;
        var len = pos - prevPos;
        word = str.substr(prevPos, len);

        if (word.length > 15) word = BreakLargeWord(word);

        words.push(word);
        words.push(match[0]);
        prevPos = pos + 1;
    }
    word = str.substr(prevPos);
    if (word.length > 15) word = BreakLargeWord(word);
    words.push(word);
    var text = words.join("");
    return text;
}

//how to use
var bigText = "Why is this text this big? Lets do a wrap <b>here</b>! aaaaaaaaaaaaa-bbbbb-eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
var goodText = BreakLargeWords(bigText);


回答12:

Add the Zero width space (&#8203;) to the string and it will wrap.

Here is a Javacript example:

let longWordWithOutSpace = 'pneumonoultramicroscopicsilicovolcanoconiosis';
// add &#8203; between every character to make it wrap
longWordWithOutSpace.split('').join('&#8203;');


回答13:

I have posted a solution which uses JavaScript and a simple Regular Expression to break long word so that it can be wrapped without breaking your website layout.

Wrap long lines using CSS and JavaScript



回答14:

I know that this is a really old problem and since I had the same problem I searched for a easy solution. As mentioned in the first post I decided to use the php-function wordwrap.

See the following code example for information ;-)

<?php
    $v = "reallyreallyreallylonglinkreallyreallyreallylonglinkreallyreallyreallylonglinkreallyreallyreallylonglinkreallyreallyreallylonglinkreallyreallyreallylonglink";
    $v2 = wordwrap($v, 12, "<br/>", true);
?>
<html>
    <head>
        <title>test</title>
    </head>
    <body>
        <table width="300" border="1">
            <tr height="30">
                <td colspan="3" align="center" valign="top">test</td>
            </tr>
            <tr>
                <td width="100"><a href="<?php echo $v; ?>"><?php echo $v2; ?></a></td>
                <td width="100">&nbsp;</td>
                <td width="100">&nbsp;</td>
            </tr>
        </table>
    </body>
</html>

Hope this helps.