Hello, I am trying to control the max length that the text appears, before it goes to the next line in a div. So I want the div to be say 100, but I want the text to only reach 50 before it wraps to the next line. Is there a way I can do this?

Dani AI

Generated

For this layout question there are two clean CSS approaches and one JS approach depending on whether you want to change layout only (visual wrap) or actually shorten the string.

  • is right: JavaScript slicing will cut the string itself (useful if you must store or send a shorter value). That is destructive to the text, so consider adding a tooltip/aria-label if you hide content.
  • ’s padding trick works visually but can be surprising: with the default box-sizing: content-box adding padding increases the element’s total width. If you want the outer box to remain exactly 100px, either use box-sizing: border-box or constrain text with an inner element.

A recommended CSS-only pattern: keep the outer container at 100px and put the text inside a child that limits the line width. This keeps layout predictable and responsive-friendly.

/* outer stays 100px */
.outer { width: 100px; box-sizing: border-box; }

/* inner limits how far text can go before wrapping */
.inner { display: block; width: 50px; overflow-wrap: break-word; }

If your goal is "about N characters per line" instead of exact pixels, ch is useful (it measures roughly the width of the "0" glyph):

.inner { max-width: 50ch; }

Extra tips: use overflow-wrap: break-word (or word-break carefully) to avoid overflow from long unbroken strings; use text-overflow: ellipsis + white-space: nowrap + overflow: hidden for single-line truncation; prefer CSS for visual layout and use JS only when you need to alter the actual content.

Recommended Answers

All 3 Replies

thx that got it working for me!

Or you could just use padding (which can be added directly to your div id)

So if your div is 100px long and you would like it to start a new line at 50px you would add

padding-right:50px

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.