今日、「CSSの高度なWeb標準ソリューションをマスターする」の例を見て、マージンについての深い理解を得ることができました:auto;。
ケースは次のとおりです。
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
#box {
width: 300px;
border: 1px solid skyblue;
display: flex;
justify-content: flex-end;
}
.one {
background: red;
margin-right: auto;
}
.two {
background: green;
}
.three {
background: blue;
}
</style>
</head>
<body>
<div id='box'>
<div class="one">one</div>
<div class="two">two</div>
<div class="three">three</div>
</div>
</body>
</html>
説明:
justify-content:flex-end;を使用すると、フレックスレイアウトのすべてのアイテムを右に移動できます。次にmargin-right:auto;を最初の要素に設定して、上記の効果を取得します。
私たちの作業で最も一般的に使用されているのはmargin:auto;ブロック要素を水平方向に中央揃えするための、つまりmargin-right:autoはどのようにしてスペース全体を占めているのですか?
マージンの充填ルールを見てみましょう:
- 片側が設定されていて片側が自動の場合、残りのスペースは自動です
- 両側が自動の場合、残りのスペースは均等に分割されます
margin-right:auto;を最初の要素でmargin:auto;に設定すると、効果は次のようになります。
別の例:
<style>
.father {
width: 300px;
background-color: #f0f3f9;
}
.son {
width: 200px;
height: 120px;
margin-right: 80px;
margin-left: auto;
background-color: #cd0000;
}
</style>
<div class="father">
<div class="son"></div>
</div>
左マージンは20px、右マージンは80pxです。ここでは、息子の幅は200px、コンテナは300px、残りの合計スペースは100pxです。このうち、margin-rightは80pxを使用し、マージンの左の「auto」の計算は残りの20pxです。
margin-left:floatではなくauto:rightで右揃えになります
.father {
width: 300px;
background-color: #f0f3f9;
}
.son {
width: 200px;
height: 120px;
margin-left: auto;
background-color: #cd0000;
}
<div class="father">
<div class="son"></div>
</div>
magin:atuoは絶対配置と連携して、水平および垂直のセンタリングを実現します
.father {
width: 300px;
height: 150px;
background-color: #f0f3f9;
position: relative;
}
.son {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 200px;
height: 100px;
background-color: #cd0000;
margin: auto;
}
<div class="father">
<div class="son"></div>
</div>
参考書「CSSワールド」