CSS, inject line break after certain number of symbols

Viewed 407

I have some text inside of a container. The container could be div, td, or even p which may look like this in browser:

Lorem ipsum dolor sit amet, consectetur adipiscing elit, 
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 

Is it possible to inject linebreaks purely by CSS after certain number of characters. for example if we should inject after 10 symbols it should look like this:

Lorem ipsu
m dolor si
t amet, co
nsectetur 
adipiscing
 elit, sed
 do eiusmo
d tempor i
ncididunt 
ut labore 
et dolore 
magna aliq
ua.

Is it possible to make this purely by CSS, without any javascript?

4 Answers

One way is to consider a monospace font where the width of all the characters is the same thus you can fix the width of the container based on this width and obtain visually what you want:

.box {
  font-family: "Inconsolata", monospace;
  width: 10ch;
  word-break: break-all;
  border:1px solid;
}
<link href="https://fonts.googleapis.com/css?family=Inconsolata" rel="stylesheet">
<div class="box">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</div>
<div class="box" style="font-size:20px;">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</div>

You can give your container a fixed width and use word-break:break-all:

.test {
  width: 75px;
  word-break: break-all;
}
<div class="test">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</div>

I would set

p, td, div {
word-break: break-all
}

and define the width in em units. I don't know if this works exactly as you want, but should help you.

You can't. The most current solution is to set your parent container width in char :

div {
 width: 10em;
}
Related