Is it possible to separate sentence to one word per line with CSS ?
Input:
<div>Hello world foo bar</div>
Rendered output:
Hello
world
foo
bar
Setting width to for example 1px
is not desired.
You have to use display:table-caption;
to achieve this.
Here is the solution.
WORKING DEMO
The HTML:
<div>Hello world foo bar</div>
The CSS:
div{display:table-caption;}
Hope this helps.
Nathan's answer using table-caption
is almost correct but misses out a key issue in that the sentence is only actually split by the longest word resulting in grouping of shorter words.
For example the following sentence:
This trick groups and splits words in a sentence based on the longest word.
actually result in the following output. Note the grouping on in a
and on the
in the output.
This
trick
groups
and
splits
words
in a
sentence
based
on the
longest
word.
You can actually do it very easily by setting the word-spacing
which has excellent support.
Using that you can output the sentence correctly as follows:
This
trick
groups
and
splits
words
in
a
sentence
based
on
the
longest
word.
Here's a working code example you can run.
Snippet
p {
word-spacing: 9999rem;
}
p ~ p {
/* Undo last assignment */
word-spacing: unset;
display: table-caption;
}
<h3>word-spacing</h3>
<p>
This trick splits each word in a sentence
</p>
<hr/>
<h3>table-caption</h3>
<p>
This trick groups and splits words in a sentence based on the longest word.
</p>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With