简体   繁体   中英

em margin not correct

i have a some problem with em units.

my base em unit is 16px

body {
    font-size:16px;
}

i try to give 30px margin-top to my h4 element.

so 30px is equal to 1.87em,

h4 {
        font-size:1.875em;
        line-height: initial;               
        margin-top: 1.87em;
    }

but when i look from web inspector computed section, there is,

margin-top:56.1px;

computed.

when i use px instead of em, like margin-top:30px; everything is normal.

why this problem happened?

IMHO, you shouldn't calculate em to pixels, but I understand it helps you to understand what you are doing. So ontopic....

You are defining a base size on your body 16px

You define a font-size for you h4, 1.875em which means: 1.875 x 16 = 30px .
These 30px are now the base size for your h4.

Meaning, the margin-top that you define on your h4 is actually 1.87 x 30 = 56.1px

So if you want a '30px margin', use margin-top: 1em on your h4.

Hope it makes sense....


As already commented by Mr. Lister, as alternative you could use rem instead of em

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM