[html] Limiting the number of characters per line with CSS

I have a paragraph of text:

<p>Lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum</p>

How can I make sure that no more than 30 characters are shown on one line with CSS?

This question is related to html css

The answer is


The latest way to go is to use the unit 'ch' which stands for character.

You can simply write:

p { max-width: 75ch; }

The only trick is that whitespaces won't be counted as characters..

Check also this post: https://stackoverflow.com/a/26975271/4069992


Depending on what font you're using you can set max-width on the paragraph with a calculated value. It will not be exact, but I've found that in most cases that does not matter.

p {
  max-width: calc(30em * 0.5);
}

The number you multiply with depends on what font it is, and how much a character takes up in a em square. More characters = less accurate.


A better solution would be you use in style css, the command to break lines. Works in older versions of browsers.

p {
word-wrap: break-word;
}

If you use CSS to select a monospace font, the problem of varying character length is easily solved.


Another approach to this would put a span element with a display:block style inside the p element each time you need the content to break. It would only be useful when your p content is static.

<p>this is a not-dynamic text and I want to put<span style="display:block">the following words in the next line</span>and these other words in a third one</p>

It would output:

This is a not-dynamic text and I want to put

the following words in the next line

and these others in a third one

This allows you to change your text line-breaks in different viewports without JS.


You could do this:
(Note! This is CSS3 and the browser support = good!! )

   p {
    text-overflow: ellipsis; /* will make [...] at the end */
    width: 370px; /* change to your preferences */
    white-space: nowrap; /* paragraph to one line */
    overflow:hidden; /* older browsers */
    }