Issue
Look at this fiddle:
function toggle(event) {
var element = document.getElementById('changeme');
element.innerText = element.innerText ? '' : 'some text';
}
button = document.getElementById('button');
button.onclick = toggle;
#changeme {
min-height: 1em;
outline: 1px solid red;
}
<input id=button type=button value='Toggle content'>
<p id=changeme>dynamically changing content
<p>This should not move (up and down)
I have a text element there (it is a <p>
, but could be a <div>
) which I sometimes set to be empty. (Use the button to toggle between empty and some content.)
What height does this element with a line of text have? I want a generic answer so I can set its min-height
to that value so that the element doesn’t collapse when empty. I thought 1em
is what I’m looking for, but 1em
seems to be the size of letters like “W” without the space below the baseline for letters like “g”.
I’m looking for a neat trick to give the possibly empty element a constant height, without putting
into it. (At the moment I use 1.5em
.)
Solution
The exact calculation of heights of lines is complicated (see CSS 2.1 section 10 Visual formatting model details), but in a simple case like this, the height is determined by the line-height
value when the element is not empty. When it is empty, the height would be empty, but the min-height
setting forces the height to the font size (1em
).
The initial value of line-height
is browser-dependent, and it is expected to depend on the font, too. The default is in practice always larger than the font size. This explains what happens here.
To keep the height constant, it is best to explicitly set its line-height
and to set min-height
to the same value, e.g.
#changeme {
line-height: 1.25em;
min-height: 1.25em;
}
Note: The em
unit means the size of the font, which is by definition the height of the font. This is a reference quantity and does not normally correspond to the height (or width) of any letter; the height of most letters is smaller than the font size (though this varies by letter and by font).
Answered By - Jukka K. Korpela
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.