I'm struggling to create a colored circle with centered text in HTML/Javascript. Here is what I am trying to achieve:
- Have a colored circle with text perfectly centered horizontally and vertically within it;
- Dynamically alter the size of the circle from JavaScript while keeping the text centered at all times.
The following code accomplishes the first part:
- Create the circle using a DIV element styled with appropriate background and border-radius;
- Add a P element inside the DIV with styles for "text-align: center" and "line-height".
For example:
p.circlecaption {
text-align: center;
line-height: 128px;
}
...
<div style="background: #a0a0a0; margin: 0px; width: 128px;
height: 128px; border-radius: 64px;" id="theCircleDiv">
<p class="circlecaption" id="theText">TEST!</p>
</div>
While this works for the static case, when attempting to change the size dynamically using JavaScript, setting the line-height property does not keep the text vertically centered as expected. For instance:
var obj = document.getElementById('theCircleDiv');
var sz = '' + (rad*2) + 'px';
obj.style.width = sz;
obj.style.height = sz;
obj.style.margin = '' + (64 - rad) + 'px';
obj = document.getElementById('theText');
obj.style['line-height'] = sz;
Unfortunately, this code resizes and re-centers the circle correctly but fails to maintain vertical alignment of the text. I have tried various solutions such as changing the property to "lineHeight" or using "vertical-align: middle", but none seem to work effectively.
If anyone can provide guidance on how to dynamically set the line-height or suggest an alternative method to keep the text centered within the circle, I would greatly appreciate it. My primary testing browser is Safari on Mac OS, but I am looking for a solution that is compatible across browsers.