JSFiddle - React, Tailwind, and code Playground
HTML
<div class="box">
<div class="title spread">Lighting</div>
<div class="subtitle spread">我是中文</div>
</div>
<div class="box">
<div class="title spread">Word Test</div>
<div class="subtitle spread">我是中文 測試</div>
</div>
CSS
.box {
width: 150px;
height: 150px;
border: 1px solid red;
margin: 6px;
}
.title {
margin-top: 40px;
height: 16px;
}
JavaScript
/**
* Text justify function
* make text justify correspond to the container
*
* @author Chan
*/
$.fn.textjustify = function() {
return this.each(function() {
var text = $(this).text(),
containerWidth = $(this).width(),
character = '',
string = '',
singleWidth = 0,
firstItemWidth = 0,
lastItemWidth = 0,
alignWidth = 0;
if ('' !== text) {
$(this).css('position', 'relative');
textArray = text.split('');
singleWidth = Math.floor(containerWidth / textArray.length);
for (i in textArray) {
// Wrapp with div to get character width
character = ('' === $.trim(textArray[i])) ? ' ' : textArray[i];
string += '<span>' + character + '</span>';
}
$(this).html(string);
firstItemWidth = $(this).find('span:first').width();
lastItemWidth = $(this).find('span:last').width();
alignWidth = containerWidth - (firstItemWidth + lastItemWidth);
$(this).find('span').each(function(i) {
if (0 === parseInt(i)) {
// The first item
$(this).css({position: 'absolute', left: 0, top: 0});
} else if ((parseInt(textArray.length) - 1) === parseInt(i)) {
// The last item
$(this).css({position: 'absolute', right: 0, top: 0});
} else {
// Other items
var left = (i * singleWidth) - $(this).width() + firstItemWidth;
$(this).css({position: 'absolute', left: left, top: 0});
}
});
}
});
}
$('.spread').textjustify();