10

I have a div that has text-align: center applied. It should be able to contain various text that may or may not wrap. When it wraps, I would like to have each line be roughly the same length, so it would show:

The quick brown fox jumps

over the lazy dog.

instead of:

The quick brown fox jumps over the lazy

dog.

Basically, I'm looking for a pure CSS way to automatically place the break near the center of the text.

I know there are JavaScript solutions, and I have currently implemented a server side solution, but I'm always trying to learn more CSS to make things more flexible in the future.

Community
  • 1
  • 1
iznevidelitsa
  • 103
  • 1
  • 6
  • 1
    What you need to do is to measure the text length, and then either insert the
    or change the width of the parent container. CSS cannot measure things, or make comparisons. I believe JS or server-side are your only options here.
    – Andrew Bacon Mar 26 '12 at 15:47
  • See https://stackoverflow.com/a/18009171/217866 – jackocnr Jul 30 '19 at 15:39
  • with html you could use [``](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/wbr). – ashleedawg Feb 10 '21 at 18:03

4 Answers4

4

Put the pieces you don't want to break in span tags that forbid wrapping:

<span style="white-space: nowrap">The quick brown fox jumps</span>
<span style="white-space: nowrap">over the lazy dog.</span>

(I know this is old, but I just went looking for this.)

lifeisfoo
  • 15,478
  • 6
  • 74
  • 115
tuxedobob
  • 223
  • 1
  • 7
4

I'm quite sure you cannot do that with css, you can control no break points with html though.

<nobr>The quick brown fox jumps</nobr><nobr>over the lazy dog.</nobr>

Should give you the result you want. Also you can stick &nbsp; between words that you don't want to wrap, for instance: The&nbsp;quick&nbsp;brown&nbsp;fox&nbsp;jump over&nbsp;the&nbsp;lazy&nbsp;dog. would give you the same result.

Yevgeniy
  • 300
  • 2
  • 7
  • [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/nobr) about ``: "Although this element is widely supported, it was never standard HTML, so you shouldn't use it." They recommend solving it with CSS. – kslstn Aug 24 '22 at 07:56
  • @kslstn thanks for pointing it out. Do you by any chance know how to do it with CSS? white-space: looks like a good option these days. – Yevgeniy Aug 30 '22 at 15:45
  • Depends a bit on your situation, but for me [tuxedobob's solution](https://stackoverflow.com/a/46180607/1171638) worked. – kslstn Aug 31 '22 at 19:00
0

function run() {
  const str = "The quick brown fox jumps over the lazy dog."
  const arr = str.split(" ")
  const num = Math.floor(arr.length / 2)

  let res = ""

  arr.map((item, i) => {
    res += item + " "
    if (num === i) res += "\n"
  })

  console.log(res)
}

run()
Yehuda Zvi
  • 239
  • 3
  • 9
-1

What if you reduce the width of your div ? Otherwise I'm not sure you can do it with CSS only

jazzytomato
  • 6,994
  • 2
  • 31
  • 44