相殺される場合
<!DOCTYPE html>
<html lang="ja" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="box">
</div>
<div class="box2">
</div>
</body>
</html>
.box {
width: 200px;
height: 200px;
margin: 20px;
border: 1px solid red;
}
.box2 {
width: 200px;
height: 200px;
margin: 20px;
border: 1px solid blue;
}
この場合boxの下marginとbox2の上marginが重なってしまっているため間隔は40pxとはならず20pxになる。
これが mrginの相殺
である。
相殺されない場合
親要素と子要素のmarginを分けられるようなborder、paddingなどをが存在する場合には相殺されない。
<div class="parent">
<div class="child">
</div>
</div>
.parent {
background-color: red;
width: 200px;
height: 100px;
border: 1px solid black;
}
.child {
background-color: blue;
width: 50%;
height: 50%;
margin-top: 20px;
}
親要素にborderがあるので、子要素のmargin-topが効く。