Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate sentence to one word per line

Tags:

css

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.

like image 414
hsz Avatar asked Aug 12 '13 10:08

hsz


2 Answers

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.

like image 126
Nitesh Avatar answered Sep 30 '22 06:09

Nitesh


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>
like image 21
James South Avatar answered Sep 30 '22 06:09

James South