flex アイテムの margin
プロパティに対して auto
を指定すると、その margin は flex コンテナ内の余白を占有するように拡張されます。
§ 9.5. Main-Axis Alignment[1]
- Distribute any remaining free space. For each flex line:
- If the remaining free space is positive and at least one main-axis margin on this line is
auto
, distribute the free space equally among these margins. Otherwise, set all auto margins to zero. - Align the items along the main-axis per
justify-content
.
§ 9.6. Cross-Axis Alignment[2]
- Resolve cross-axis auto margins. If a flex item has
auto
cross-axis margins:
- If its outer cross size (treating those
auto
margins as zero) is less than the cross size of its flex line, distribute the difference in those sizes equally to the auto margins. - Otherwise, if the
block-start
orinline-start
margin (whichever is in the cross axis) isauto
, set it to zero. Set the opposite margin so that the outer cross size of the item equals the cross size of its flex line.
これを利用して、 i
要素を flex コンテナに設定した上で、 before
擬似要素の margin
プロパティに対して auto
を設定することで、以下のように行うことが出来ます。
html {
text-align: center;
}
/* リセット */
button {
background: none;
border: 0;
outline: none;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
#a,
#d {
display: none;
}
ul {
display: inline-flex;
}
.buttons {
margin: 0 1em;
cursor: pointer;
display: inline-block;
}
i.icons {
display: flex; /* 追記 */
font-size: 40px;
width: 80px;
height: 80px;
border: 2px solid black;
vertical-align: middle;
}
i.icons::before {
margin: auto; /* 追記 */
}
.check:checked+i {
color: red;
border: 2px solid red;
}
<link href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
<nav id="buttonWrap">
<ul id="list">
<li>
<label for="a" class="buttons">
<input type="checkbox" id="a" class="check">
<i class="fas fa-check icons"></i>
<p>A</p>
</label>
</li>
<li>
<button class="buttons">
<i class="fas fa-check icons"></i>
<p>B</p>
</button>
</li>
<li>
<button class="buttons">
<i class="fas fa-check icons"></i>
<p>C</p>
</button>
</li>
<li>
<label for="d" class="buttons">
<input type="checkbox" id="d" class="check">
<i class="fas fa-check icons"></i>
<p>D</p>
</label>
</li>
</ul>
</nav>