Dynamically setting line-height/keeping text vertically centered when parent div changes size in JavaScript
css, javascript
Solution
Here is an example. I'm using jQuery UI to wire up some dynamic setting of the size but the re-size code should work in a pure JavaScript environment.
First, I cleaned up the HTML and put it's style in CSS
HTML:
<div id="theCircleDiv">
<p class="circlecaption" id="theText">TEST!</p>
</div>
CSS:
#theText {
text-align: center;
line-height: 128px;
}
#theCircleDiv {
background: #a0a0a0;
margin: 0px;
width: 128px;
height: 128px;
border-radius: 64px;
}
JavaScript:
function resize(size) {
var circle = document.getElementById('theCircleDiv'),
text = document.getElementById('theText');
circle.style.width = size + 'px';
circle.style.height = size + 'px';
circle.style.borderRadius = (size / 2) + 'px';
text.style.lineHeight = size + 'px';
}
Problem
I'm trying to achieve the following in HTML/Javascript: - have a coloured circle with a piece of text perfectly centred (both horizontally and vertically) within it; - dynamically from JavaScript, be able to alter the size of the circle, maintaining the text centred within it at all times. The following achieves the first of these: - Create the circle using a DIV element whose style has appropriate background and border-radius; - Inside the DIV, put a P element whose style has "text-aligbn: 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> ``` This works fine for the initial, static, case. The problem comes when, from JavaScript, I attempt to set the line-height property in order to keep the text vertically centred as I change the size of the div. I expected something like the following to work: ``` 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; ``` However, while this code re-sizes and re-centres the circle perfectly, it doesn't vertically re-centre the text-- i.e. the attempt to dynamically set line-height appears to be ignored. Can anybody offer any help on either how to set line-height dynamically, or else a way to achieve my desired goal of keeping the text centred within the circle? From my reading around, I've seen various other suggestions such as calling the property "lineHeight" or playing around with "vertical-align: middle", but none seems to work. (I am currently testing in Safari on Mac OS which is likely to be most used among the site's target audience, but am also looking for a solution that is reasonably cross-browser compatible.)