I am trying to resize a font of an element so its text properly fit in the container, and I came up with this for-loop. I am afraid this might run into performance issue so I was wondering if there's a better approach - preferably without Javascript?
const txt = $("#text");
const box = $("#box");
let size = 5; // minimum font size
let found = false;
do {
txt.css('font-size', `${size}pt`);
if(txt.height() < box.height() && txt.width() < box.width()) {
size+=.1;
} else {
found = true;
}
} while(!found);
#box {
background-color: green;
display: block;
height: 120px;
width: 100%;
}
#text {
background:red;
display: inline;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="box">
<div id="text">
This is a sample test. This is a sample test.<br />
This is a sample test. This is a sample test.<br />
This is a sample test. This is a sample test.
</div>
</div>