# em

[CSS](https://lochiwei.gitbook.io/web/css) ⟩ [values](https://lochiwei.gitbook.io/web/css/values) ⟩ [relative](https://lochiwei.gitbook.io/web/css/values/unit/relative) ⟩ [units](https://lochiwei.gitbook.io/web/css/values/unit) ⟩ <mark style="color:purple;">`em`</mark>

{% hint style="info" %} <mark style="color:purple;">**`em`**</mark> = 自己的 <mark style="color:blue;">`font-size`</mark> (可能是<mark style="color:yellow;">自己設定</mark>，或<mark style="color:orange;">繼承</mark>來的)
{% endhint %}

{% hint style="warning" %}
當元素<mark style="color:yellow;">多層嵌套</mark>同時使用 <mark style="color:purple;">**`em`**</mark>，<mark style="color:red;">會導致累積效應</mark>，這種行為稱為「<mark style="color:orange;">複合繼承</mark>」。使用 [`rem`](https://lochiwei.gitbook.io/web/css/values/unit/relative/rem) 可以避免這種累積效應，較為穩定。
{% endhint %}

{% tabs %}
{% tab title="💾 程式" %}
📁 css  :point\_right: [codepen](https://codepen.io/pegasusroe/pen/emOWZPW)

```css
/* em = 自己的 font-size (自己設定或繼承來) */
html    { font-size: 16px;  }    /* em = 16px */

div     { font-size: 2em;   }    /*   2em = 2   * 16px = 32px */
p       { font-size: 0.5em; }    /* 0.5em = 0.5 * 32px = 16px */
p.case2 { font-size: 1.5em; }    /* 1.5em = 1.5 * 32px = 48px */
```

📁 html

```html
<div>
	<!--  em = <html> font-size = 16px -->
	<!-- 2em = 2 * 16px         = 32px -->
	div: 2em = 32px (html: em = 16px)
	<p>
		<!--    em = <div> font-size = 32px -->
		<!-- 0.5em = 0.5 * 32px      = 16px -->
		p: 0.5em = 16px (div: em = 32px)
	</p>
</div>

<div>
	div: 2em = 32px (html: em = 16px)
	<p class="case2">
		<!--    em = <div> font-size = 32px -->
		<!-- 1.5em = 1.5 * 32px      = 48px -->
		p: 1.5em = 48px (div: em = 32px)
	</p>
</div>
```

{% endtab %}

{% tab title="👥 相關" %}

* 用 <mark style="color:purple;">**`em`**</mark> <mark style="color:red;">會導致累積效應</mark>，用 [rem](https://lochiwei.gitbook.io/web/css/values/unit/relative/rem "mention") <mark style="color:green;">可避免</mark>這種效應。
  {% endtab %}

{% tab title="📘 手冊" %}

* MDN ⟩ [CSS values and units](https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Styling_basics/Values_and_units)&#x20;
  {% endtab %}

{% tab title="📗 參考" %}

* [一次搞懂 CSS 字體單位：px、em、rem 和 %](https://www.oxxostudio.tw/articles/201809/css-font-size.html)
  {% endtab %}

{% tab title="💈範例" %}
{% embed url="<https://codepen.io/pegasusroe/pen/emOWZPW>" %}
{% endtab %}
{% endtabs %}
