JSFiddle - React, Tailwind, and code Playground
by viphalongpro
HTML
<h3>Original column</h3>
<div class='o-column'>racket kingpins are rounded up in bomb killing</div>
<h3>Column after adjusted</h3>
<div class='column'>racket kingpins are rounded up in bomb killing</div>
CSS
.column, .o-column {
width:300px;
border:1px solid black;
margin-bottom:5px;
text-transform:uppercase;
padding:5px;
font-size:30px;
font-family:'Arial';
word-wrap:break-word;
}
JavaScript
console.clear();
var column = document.querySelector('.column');
var ends = [];
var range = document.createRange();
range.selectNodeContents(column);
var lines = [];
var lastBottom = null;
//if the innerHTML has some \n character, there will be some unexpected
//behavior, all the \n characters should be removed first.
column.innerHTML = column.innerHTML.replace(/\n/g,'');
//column.innerHTML = column.innerHTML.replace(/ /g,'');
//document.querySelector('.o-column').innerHTML = document.querySelector('.o-column').innerHTML.replace(/ /g,'');
var len = column.innerHTML.length;
for(var i = 0; i < len; i++){
//set range for current character
range.setStart(column.childNodes[0],i);
range.setEnd(column.childNodes[0],i+1);
var rect = range.getBoundingClientRect();
if((rect.bottom == 0 && rect.top == 0) ||
rect.bottom != lastBottom && lastBottom != null || i == len-1){
var line = document.createElement('div');
var lineStart = ends.length ? ends[ends.length - 1] + 1 : 0;
line.innerHTML = column.innerHTML.substring(lineStart, i == len - 1 ? len : i);//should be rect.bottom ? i : i + 1;
lines.push(line);
ends.push(rect.bottom ? i - 1 : i);
}
if(rect.bottom != 0) lastBottom = rect.bottom;
else lastBottom = null;
if(ends.length > 3) break;
}
var n = lines.length;
if(n < 4 && n > 0){
column.innerHTML = "";
for(var i = 0; i < n; i++){
column.appendChild(lines[i]);
}
if(n == 1) lines[0].style.textAlign = 'center';
else {
lines[0].style.textAlign = 'left';
lines[n-1].style.textAlign = 'right';
if(n == 3) lines[1].style.textAlign = 'center';
}
}