'How is it possible to create a circle in CSS that always keeps the same size?
I have the problem that I have a circle that adjusts according to the content of the text. However, I would like the font size to adjust to the circle and not have the circle change size.
How is it possible to implement this in CSS? I use react 18 and styled-components.
Examples of how it should not be.
Please note that the circle should remain a circle on any device.
I hope for your ideas
Solution 1:[1]
I think you are going to need a bit of avaScript for this.
Here's a simple example. The size of the text is gradually increased until it is wider than you want, then decreased by 1 for the texts in each circle.
const tester = document.createElement('div');
tester.setAttribute('class', 'tester');
document.body.append(tester);
const circles = document.querySelectorAll('.circle');
circles.forEach(circle => {
  let fs = 2; // 1px is the smallest we can go
  tester.innerHTML = circle.innerHTML;
  tester.style.fontSize = fs + 'px';
  let w = window.getComputedStyle(tester).width.replace('px', '');
  while (w < 40) { //allow for some space left and right so not the full 50
    fs++;
    tester.style.fontSize = fs + 'px';
    w = window.getComputedStyle(tester).width.replace('px', '');
  };
  circle.style.fontSize = (fs - 1) + 'px';
});
tester.remove();
.circle {
  color: white;
  background-color: darkblue;
  border-radius: 50%;
  width: 50px;
  aspect-ratio: 1 / 1;
  display: flex;
  justify-content: center;
  align-items: center;
}
.tester {
  width: fit-content;
  position: absolute;
}
<div class="circle">text</div>
<div class="circle">longer text</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source | 
|---|---|
| Solution 1 | A Haworth | 
