Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

前端设计单位 #27

Open
yanyue404 opened this issue May 23, 2018 · 0 comments
Open

前端设计单位 #27

yanyue404 opened this issue May 23, 2018 · 0 comments
Labels

Comments

@yanyue404
Copy link
Owner

yanyue404 commented May 23, 2018

普遍原理

em是相对于文本字体大小来度量的;rem则是相对于html元素根节点的大小来度量的.

em

在当em和px单位混用时候

  • p元素与h1元素平级 => em参照16px计算
   <h1>这是一段文字</h1>
   <p>这是第二段文字</p>
h1 {
    font-size: 20px;
}
p {
    font-size: 2em; /*2em = 32px*/
}
  • p元素与h1元素被div包含=》按照div
<div>
    <h1>这是一段文字</h1>
    <p>这是第二段文字</p>
</div>
div {
    font-size: 18px; /*1em = 18px*/
}
h1 {
    font-size: 20px 
}
p {
    font-size: 2em; /*2em = 36px*/
}
  • html结构不变,为html添加font-size属性,甚至!important=>div

证明与rem单位不一样,不听从html根节点的

html {
    font-size: 16px;
}
div {
    font-size: 18px; /*1em = 18px*/
}
h1 {
    font-size: 20px 
}
p {
    font-size: 2em; /*2em = 36px*/
}

都是em听谁的?

 h1 {
    font-size: 2em;     /* 1em = 16px */
    margin-bottom: 1em; /* 1em = 32px */
}

p {
    font-size: 1em;    /* 1em = 16px */
    margin-bottom: 1em;/* 1em = 16px */
}

上述h1和p的margin-bottom都是1em,但是外边距的结果值却不相同。上述现象的出现,是因为em是相对于当前元素字体的大小。由于h1中字体大小设置为2em,因此h1中其他属性的1em值就是1em=32px.

rem

h1 {
  font-size: 2rem;
  margin-bottom: 1rem; /* 1rem = 16px */
}
p {
  font-size: 1rem;
  margin-bottom: 1rem; /* 1rem = 16px */
}

1rem总是等于16px(除非html根元素字体大小改变)

使用em和rem

总结

究竟是该使用em还是rem呢?答案应该是结合使用em和rem。当属性值的大小需要根据当前元素字体尺寸缩放时,就选用em,其它的情况都使用更简单的rem。

62.5%

常用字体值表示rem(基本字体尺寸为16px)

10px = 0.625rem
12px = 0.75rem
14px = 0.875rem
16px = 1rem (base)
18px = 1.125rem
20px = 1.25rem
24px = 1.5rem
30px = 1.875rem
32px = 2rem

通过62.5%的设定,就可以很容易用em或者rem来定义具体属性的尺寸了(10倍的关系)。

em

body { font-size:62.5%; }  /* =10px */
h1   { font-size: 2.4em; } /* =24px */
p    { font-size: 1.4em; } /* =14px */

rem

html { font-size: 62.5%; }  /* =10px */
body { font-size: 1.4rem; } /* =14px */
h1   { font-size: 2.4rem; } /* =24px */

参考

@yanyue404 yanyue404 added the Css label May 23, 2018
@yanyue404 yanyue404 added Css and removed Css labels Sep 2, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant