Question

I want to break my strings like this, using css:

Input:

this,is,a,bad,punctuaction,example.

Output:

this,is,a,bad,
punctuation,
example.

Possible?

Was it helpful?

Solution

Yes possible if you wrap each word in a span element as shown in the below example:

HTML

<div><span>this,</span><span>is,</span><span>a,</span><span>bad,</span>
<span>punctuation,</span><span>example.</span>
</div>

CSS

div {
    width: 30%;
    border: 1px solid red;
    overflow: hidden;
}
div span {
    float: left;
}

Working Fiddle

otherwise, you need to look in to javascript.

JS (example):

var div = document.getElementById('main');
div.innerHTML = "<span>" + div.innerHTML.split(",").join(",</span><span>") + "</span>"; 

Working Fiddle

OTHER TIPS

In 2018, this can be done with CSS:

.dont-break-out {
  /* These are technically the same, but use both */
  overflow-wrap: break-word;
  word-wrap: break-word;

  -ms-word-break: break-all;
  /* This is the dangerous one in WebKit, as it breaks things wherever */
  word-break: break-all;
  /* Instead use this non-standard one: */
  word-break: break-word;

  /* Adds a hyphen where the word breaks, if supported (No Blink) */
  -ms-hyphens: auto;
  -moz-hyphens: auto;
  -webkit-hyphens: auto;
  hyphens: auto;
}

See https://css-tricks.com/snippets/css/prevent-long-urls-from-breaking-out-of-container/ for a more complete answer.

There are several ways to allow line breaks where they would not otherwise be allowed, but no way in CSS alone. The reason is that CSS works on elements, not characters.

The most robust HTML+CSS way is probably to insert the following after each comma (or other character after which a line break should be allowed):

<wbr><a class=wbr></a>

with the CSS setting

.wbr:after { content: "\00200B"; }

This is a tricky issue, see longish explanations.

div span {
float: left;
word-wrap: break-word;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top