0

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>
Raisen
  • 4,225
  • 2
  • 22
  • 36
  • This might help you some day: https://wicg.github.io/container-queries/ – connexo Jun 28 '19 at 18:45
  • Aside from that, I agree your approach is going to kill the performance. Yet it's the only thing you have. – connexo Jun 28 '19 at 18:51
  • 2
    You can do bigger steps and when you go over, go smaller.... – epascarello Jun 28 '19 at 18:57
  • I deleted my answer and linked to a very good duplicate, showing the same trick I posted, using `vw`, and then some... – Asons Jun 28 '19 at 19:14
  • Most of the answers I found on SO are related to vw/vh, but that doesn't work in all cases. If you plug vw/vh on my sample code, you'll see it doesn't work as expected. – Raisen Jun 28 '19 at 23:10

0 Answers0