Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

html - Why would the height increase with a smaller font size?

I have a block with a certain line-height, where I insert content with the ::before pseudo element.

.block::before {
  content:'text here';
}

This works well. However, if I also give the content a smaller font size

.block::before {
  font-size:.6em;
  content:'text here';
}

the block actually becomes higher. Why is that?

.container {
    display:inline-block;
}
.lorem, .ipsum, .dolor, .sit {
    line-height:3em; border:1px solid green
}
.ipsum:before {
    content:'world!';
}
.sit:before {
    font-size:.6em;
    content:'world!';
}
<div class="container">
    <div class="lorem">Hello</div>
</div>
<div class="container">
    <div class="ipsum"></div>
</div>
<hr style="clear:both"/>
<div class="container">
    <div class="dolor">Hello</div>
</div>
<div class="container">
    <div class="sit"></div>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Edit: This question has had quite a number of new eyeballs lately, so here's an update to make it more useful.


Alohci's solution is correct, but it may not be absolutely clear for the more graphically-inclined.

So allow me to clarify the solution a bit, with pictures.

First, the line-height is inherited as its calculated size, so although it's specified in em units, children will inherit value in pixels. For example, with a font size of 20px and a line height of 3em, the line height will be 60 pixels, even for descendants with different font sizes (unless they specify their own line heights).

Now let's assume a font with a 1/4 descender. That is, if you have a 20px font, the descender is 5 pixels and the ascender 15 pixels. The remaining line-height (in this case, 40 pixels) is then divided equally above and below the baseline, like this.

font 20px with a line height of 60px

For the block with the smaller font (0.6em or 12 pixels), the remaining amount of line-height is 60-12 or 48 pixels, which also gets divided equally: 24 above and 24 below the baseline.

font 0.6em or 12 pixels, also with a line height of 60 pixels

Then if we combine the two fonts on the same baseline, you will see that the line heights are not divided in the same way, so the total height of the containing block increases, even though both line heights are 60 pixels.

both fonts

Hope this explains things!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...