0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

仕様書を読もう(CSS編①)継承プロパティの%指定

Posted at

本シリーズは、エンジニアとしての実力不足を常日頃から感じている私が、仕様書(日本語訳)を読み、得た知識をアウトプットしていくためのものとなっております。

前提知識 : プロパティの継承

要素に指定したプロパティが継承プロパティであった場合、その要素自身に適用したプロパティ値を、子孫要素に対しても継承します。

html
<div class="parent">
  <p class="child">子要素内の文字</p>
</div>

<style>
  .parent {
    color: red;
  }
</style>

上記の場合、colorは継承プロパティのため、親の.parent要素に指定したcolor: red;が、子の.child要素に対しても適用されます。
widthなどの非継承プロパティの場合は、指定した要素自身にしか値は適用されません。

本題 : %指定のプロパティ値が継承される場合、%指定のままではなく、”算出値”で継承される

html
  <div class="parent">
    <p class="child">子要素内の文字</p>
  </div>

  <style>
    .parent {
      font-size: 60px;
      line-height: 120%;
      background-color: rgb(255, 127, 127);
    }
    .child {
      font-size: 20px;
    }
  </style>

例えば、上記のような場合、line-heightは継承プロパティのため、.childにもline-height: 120%;が適用されます。

CleanShot 2025-08-29 at 15.02.55@2x.png

ですが、↓のように.childに対して同値を明示的に指定すると……

html
  <div class="parent">
    <p class="child">子要素内の文字</p>
  </div>

  <style>
    .parent {
      font-size: 60px;
      line-height: 120%;
      background-color: rgb(255, 127, 127);
    }
    .child {
      font-size: 20px;
+     line-height: 120%;
    }
  </style>

CleanShot 2025-08-29 at 15.07.48@2x.png

明らかに違いますね?どちらも、.childline-height: 120%;が適用されているため、アウトプットも同じにならなければならないはずです。
なぜ、このような差異が生じるのでしょうか?その原因は、CSSにおける「%」という単位の仕様にあります。

(一般に)子要素は親の算出値を継承するので、次の例では、P要素の子が継承する'line-height'の値はパーセント値(120%)ではなく12pxとなる

p { font-size: 10px }
p { line-height: 120% } /* 'font-size'の120% */

つまり、一つ目の例では、.parentから.childline-height: 120%;がそのまま継承されるのではなく、 line-height: 72px;という”算出値”として継承されている のです。
二つ目の例では、.childに対して明示的にline-height: 120%;を指定したことで、line-height: 24px;として再算出されているわけですね。

ちなみに、line-height: 1.2とした場合は、.childに対する指定の有無でアウトプットが変わらないんですよね……🤔こっちの場合は、継承元ではなく要素自身のfont-sizeで算出してくれるっぽいです。上手く使い分けたい所ですね。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?