
目次
marginプロパティを使って解決
この現象はmarginプロパティにマイナスの値を設定することによって解決します。上方向に100pxずらして下の要素を詰めて表示したい場合を想定して解説します。 この場合はmargin-bottomプロパティに対して-100pxを指定します。 以下のコードを基に解説します。
HTML
<div class="container">
<div class="circle"></div>
<div class="square"></div>
</div>
CSS
.container{
width: 500px;
height: 900px;
}
.circle, .square{
width: 300px;
height: 300px;
}
.circle{
background-color: skyblue;
border-radius: 50%;
}
.square{
background-color: orange;
}
解説
[1] 何もしていない状態(初期状態)
[2] 円を100px上にあげる
position: relative;
bottom: 100px;
[3] margin-bottomにマイナスの値を指定して余白を詰める
この例では.circleに対して以下のコードを追加しています。
margin-bottom: -100px;
最終的なCSS
.container{
width: 500px;
height: 900px;
}
.circle, .square{
width: 300px;
height: 300px;
}
.circle{
background-color: skyblue;
border-radius: 50%;
position: relative;
bottom: 100px;
margin-bottom: -100px;
}
.square{
background-color: orange;
}
このようにすれば、たとえpositionプロパティを使った際余白ができても要素を詰めることができます。