1

I want to scale the font of the text in the circle if it overflows. If it is overflowed I want the text to resized until it fits inside the circle. I'll eventually be coding in dynamic text, so I need to find a solution that is able to check overflow every time it's re-rendered.

enter image description here

I've been trying to do this with Javascript and React.js, however I'm having a hard time finding a solution. My current idea is to create a function called changeFontSize and do a conditional where I check if the text width is greater than the circle width. Then keep decreasing the size until the text fits.

I'm still quite new to Javascript, so I'm unsure how to execute this. I want to be able to do this without calling in a package to handle it for me.

.circle { 
  justify-content: center;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: 2px solid red;
  line-height:50px;
  text-align:center;
}
<div class="circle">circleCIRCLEcircle</div>
Fury
  • 23
  • 7
  • Checking against the circle width won't help if you text is not centered exactly across the diagonal (and even then you'd have to make a bit of an adjustment). You'll need to know exactly where the text is to be placed vertically - in your picture it is part way down only. What is the positioning? – A Haworth May 19 '22 at 07:11
  • https://css-tricks.com/using-css-to-set-text-inside-a-circle/ this might help you. – Crystal May 19 '22 at 07:33
  • I'm going to be positioning the text in the centre of the circle. – Fury May 19 '22 at 23:03

2 Answers2

0

There's a great npm package called fitty that will fit the text to the size of the container automatically:

<div id="my-element">Hello World</div>

<script src="fitty.min.js"></script>
<script>
    fitty('#my-element');
</script>
Joseph
  • 691
  • 4
  • 18
-2

      .circle {
        border-radius: 50%;
        width:100px;
        height: 100px;
        padding: 10px;
        background: #fff;
        border: 3px solid #000;
        color: #000;
        text-align: center;
        font: 32px Arial, sans-serif;
        word-break: break-word;
        white-space: break-spaces;
 <div class="circle">circleCirlcecircle</div>