Home > Software engineering >  How do I maintain a consistent (but unknown) width when performing word wrap using pure HTML CSS?
How do I maintain a consistent (but unknown) width when performing word wrap using pure HTML CSS?

Time:03-08

This was a very hard question to Google since there are lot of similar problems with similar wordings. To be specific, what I'm after is purely for aesthetic purposes:

A long string can wrap like
this.

...but:

I would prefer it
to wrap like this.

Note that though these are both two lines, they do not necessarily need to be two lines. Shorter lines will still appear as normal:

Short Title...

...and you could have even longer lines:

This is what a
solution might
look like if it
spanned multiple
lines.

Here's the exact problem I'm trying to solve.

I'd prefer it to balance the length of each line, even if there is more space on the left and right side of the text. The idea is that each line has a consistent width with the one above it.

The problem is that the text to be wrapped is dynamic and can have any length. I wonder if there is a way to do this non-programmatically.

I believe there should be a few ways to do this in JavaScript but first I'd like to exhaust my options with modern HTML and CSS.

Thanks!

CodePudding user response:

I think if you use div and change his width

<!DOCTYPE html>
<html>
 <head>
  <style>
   .myDiv {    
    text-align: center;
    width: 100px;
   }
  </style>
 </head>
 <body>
  <h1>Normal text Normal text Normal text</h1>
  <div >
   <h2>Div text Div text Div text Div text Div text Div text</h2>
  </div>
  <h1>Normal text Normal text Normal text</h1>
 </body>
</html>

Doing it in the same css and html is probably impossible but I found using javascript

Here you have the link

CodePudding user response:

Maybe use the css ch unit and a use of javascript.

The use of filter is to remove the white space.

function divide(line){
const length = document.querySelector('div').textContent.split('').filter(i=>i!=" ").length;
document.querySelector('div').style.width = `${length/line}ch`
}
divide(3)
<div>I would prefer it to wrap like this.</div>

function divide(line) {
  const length = document.querySelector('div').textContent.split('').filter(i => i != " ").length;
  document.querySelector('div').style.width = `${length/line}ch`
}
divide(4)
<div>This is what a solution might look like if it spanned multiple lines.
</div>

  • Related