Some common font size font units and line height in CSS

Time:2021-4-18

PX (pixel) pixel

I believe you are not unfamiliar with the term pixel. Next, let’s introduce some small knowledge points of this unit

Pixel is composed of two words: picture and element. Pixel is not an absolute unit of natural length. For example, the same size of 1px has different “natural length” on different devices. When you zoom in on an image, you will find that the image is composed of small blocks, each of which is 1px, The larger the magnification, the larger the natural length of 1px. Therefore, the more pixels in the same natural length image, the clearer the image

em

Relative to the font size of the text in the current object, it can also be understood as a percentage unit, 1em = 100%

If the font size is not set for the current child element (the default browser font size is 16px), then the child element sets the font size:font-size:1em;In this case, the font size of the child element is 100% X 16px = 16px of the parent element, and so on,font-size:1.5em;The font size of the sub elements is 24px;

p{
    font-size:1.5em;
}
div{
    font-size:1.5em;
}
<div>
    <p>
        font size
    </p>
</div>

The “font size” here is 1.5 x 1.5 x 16 = 36px

The font size of the parent element is inherited from the child element, but it inherits the PX value, not the EM value?

body{2em}


<body>
    <div>
        <p></p>
    </div>
</body>

So the sub elements div and P in the body are 32px (no superposition)

rem

The reference object of REM is not the parent element, so no matter how the parent element changes, the font size of the element currently set REM will not respond

Rem is changed relative to the value of the root element (that is, HTML). When we write HTML documents, the head and body are wrapped by < HTML > < / HTML > tags

In CSS style, we can also change the font size of HTML


html{
    font-size:10px;
}
div{
    font-size:2rem;
}

In this case, the font size of div is 20px;

Line height directly writes numbers in CSS Style

aboutfont-sizeIt is wrong for us to do this and we will not respond

howeverline-heightIn addition to the above unit settings, you can write numbers directly without setting units

In line height, EM is also a proportion of the current font size. It inherits the fixed value of PX, and the child element does not inherit the value of EM

howeverline-height:2;It can be inherited. After the child element inherits this, the line height value is twice the current font size

summary

This article about some commonly used font size font units and line height in CSS is introduced here. For more related content of CSS font size and line height, please search previous articles of developer or continue to browse the following related articles. I hope you can support developer more in the future!