JSFiddle - React, Tailwind, and code Playground
HTML
<div class="wrapper">
<div class="shrunken">testing testing</div>
</div>
<div class="wrapper">
<div class="shrunken fixed">testing testing</div>
</div>
<div class="wrapper">
<div class="shrunken">testing</div>
</div>
<div class="wrapper">
<div class="shrunken fixed">testing</div>
</div>
<div class="wrapper">
<div class="shrunken" >testing 123 testing </div>
</div>
<div class="wrapper">
<div class="shrunken fixed" >testing 123 testing </div>
</div>
CSS
.wrapper {text-align: center; background-color: #eee; overflow: auto; padding: 20px 0;}
.shrunken {display: inline-block; font-size: 24px; background-color: #ddd; max-width: 130px; }
JavaScript
$.fn.fixWidth = function () {
$(this).each(function () {
var el = $(this);
var getLength = function (txt) {
var span = new $("<span />");
if (txt == ' ')
span.html(' ');
else
span.text(txt);
el.append(span);
var len = span.width();
span.remove();
return len;
};
var words = el.text().split(' ');
var lengthOfSpace = getLength(' ');
var lengthOfLine = 0;
var maxElementWidth = el.width();
var maxLineLengthSoFar = 0;
for (var i = 0; i < words.length; i++) {
var curWord = getLength(words[i]);
if ((lengthOfLine + (i == 0 ? 0 : lengthOfSpace) + curWord) > maxElementWidth) {
if (lengthOfLine > maxLineLengthSoFar) {
maxLineLengthSoFar = lengthOfLine;
lengthOfLine = 0;
}
}
else
lengthOfLine += (i == 0 ? 0 : lengthOfSpace) + curWord;
}
if (maxLineLengthSoFar != 0)
el.css({ width: maxLineLengthSoFar + "px" });
});
};
$(function () {
$(".fixed").fixWidth();
});