CSS inheritでマージン(margin)の値を継承する方法

環境
Google Chrome 111.0.5563.65(Official Build)
Windows 10 Home 64bit

書式
.クラス名{
marginの値: inherit;
paddingの値: inherit;
}
inheritを使用すると強制的に値を継承させることができます。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<head>
<style>
.tA {
border: solid 3px green;
}
.tB {
margin-left: 20px;
border: solid 3px yellow;
}
.tC {
margin-left: inherit;/*親要素のクラスtB継承*/
border: solid 3px blue;
}
</style>
</head>
<body>
<div class="tA">
tokyo
<div class="tB">
oosaka
<div class="tC">fukuoka</div>
</div>
</div>
</body>
</html>
<!DOCTYPE html> <html> <head> <style> .tA { border: solid 3px green; } .tB { margin-left: 20px; border: solid 3px yellow; } .tC { margin-left: inherit;/*親要素のクラスtB継承*/ border: solid 3px blue; } </style> </head> <body> <div class="tA"> tokyo <div class="tB"> oosaka <div class="tC">fukuoka</div> </div> </div> </body> </html>
<!DOCTYPE html>
<html>
<head>
<style>
  .tA {
    border: solid 3px green;
  }
  .tB {
    margin-left: 20px;
    border: solid 3px yellow;
  }
  .tC {
    margin-left: inherit;/*親要素のクラスtB継承*/
    border: solid 3px blue;
  }
</style>
</head>
<body>

<div class="tA">
  tokyo
  <div class="tB">
    oosaka
    <div class="tC">fukuoka</div>
  </div>
</div>

</body>
</html>

結果
クラスtCのinheritのため親要素のクラスtBのマージン(margin-left)が継承されます。
tCの左側のマージンに20pxの幅があります。

CSS

Posted by arkgame