【问题标题】:What is the difference between % and em?% 和 em 有什么区别?
【发布时间】:2017-05-14 11:21:30
【问题描述】:

% 和 em 长度值有什么区别?如果包含元素的字体大小为 10px,则 1em = 10px,100% = 10px。 Stackoverflow 中的答案都没有回答这个特定的问题。

【问题讨论】:

标签: css


【解决方案1】:

em 是对相关元素当前字体大小的相对度量。 1em 等于相关元素的当前字体大小。

如果您没有在页面的任何位置设置字体大小,那么它将是浏览器的默认值,可能是 16 像素。所以默认情况下 1em = 16px。如果你要在你的身体上设置一个 20px 的字体大小,那么 1em = 20px。

% 但是不依赖于任何特定属性。当您将其应用于不同的属性时,它的参考会发生变化。

看这个例子:

section{
  width:100%;
}
div{
  width:50px;
  height:50px;
  margin:0;
  padding:0;
}
.a{
  background-color:red;
}
.b{
  background-color:blue;
  width:2em;
}
.c{
  background-color:green;
  width:50%;
}
<section>
<div class="a">A</div>
<div class="b">B</div>
<div class="c">C</div>
</section>

【讨论】:

  • B=100px, A=?, C=?
  • A=50px B=(2*16=32px) C= 50%of screen size
  • 因为100%=full size it can extend,就是它的父元素的大小
  • C 的父元素是覆盖全屏的部分。所以如果屏幕宽度是 800px 那么C 的宽度将是 400px
  • 所以简而言之,2em 是其字体大小的两倍,但 200% 是其父级大小的两倍
【解决方案2】:

em 单元依赖于font-size。 它可用于适合大小更改/缩放的文本。

在下面的sn-p中你可以看到区别:

let list = document.querySelectorAll('.fs');

let fs = 10;
setInterval(() => {
  if (fs > 36) fs = 10;
  list.forEach(el => el.style.fontSize = fs+'pt');
  fs += 1;
}, 100)
.em {
  width: 2em;
  background-color: cyan;
}
.perc {
  width: 10%;
  background-color: pink;
}
<div class="em fs">2em</div>
<div class="perc fs">10%</div>

【讨论】:

  • % 取决于什么?
  • 在最近的父 position:relative/absolute 容器大小上。在我的 sn-p 中,它是 document.body 宽度
猜你喜欢
  • 2011-01-24
  • 2010-10-12
  • 2010-12-28
  • 1970-01-01
  • 1970-01-01
  • 2016-12-08
  • 2015-10-03
  • 2010-10-02
  • 2011-12-12
相关资源
最近更新 更多