CSSのplace-items:centerで上下中央揃え
Webサイトを制作していると、以下のように特定の親要素内の子要素を上下中央揃えにしたいことがあります。
<div class="content">
<div class="sample">sample</div>
</div>
このような配置は最近だと「display: grid」と「place-items: center;」を使用して作成されることが多いです。
.content {
display: grid;
place-items: center;
width: 200px;
height: 150px;
border: 1px solid #CCC;
}
.sample {
padding: 10px;
background: skyblue;
}
この作り方だと「display: grid」と「place-items: center」の2つのプロパティだけで作成できるので便利です。
しかし、Safariだと特定の条件下では上下中央揃えにならないので注意が必要です。
Safariはaspect-ratioだけの指定だと効かない
Safariだと親要素にaspect-ratioだけ指定されている場合は、「display: grid」と「place-items: center;」の2つのプロパティを指定しても上下中央揃えになりません。
<div class="box">
<div class="sample">sample</div>
</div>
.box {
display: grid;
place-items: center;
aspect-ratio: 4 / 1;
border: 1px solid #CCC;
}
.sample {
padding: 10px;
background: skyblue;
}
※ このHTML&CSSだとSafariだと下図のように上下中央揃えになりません。
Safariのバグの解決方法
この問題を解決するには、aspect-ratioを指定している要素にwidthを指定します。
Safariで「aspect-ratio: 4 / 1」だけ指定されていると、高さを計算して認識できず、「place-items: center」が効きません。
「align-content: center」などでも直りますが、「place-items: center」を指定しているので、widthで直したほうが良いでしょう。
<div class="box-fix">
<div class="sample">sample</div>
</div>
.box-fix {
display: grid;
place-items: center;
aspect-ratio: 4 / 1;
width: 100%;
border: 1px solid #CCC;
}
.sample {
padding: 10px;
background: skyblue;
}
結構前から発生しているバグなのですが、2024年4月現在の最新バージョンSafari 17.4.1でも発生しているので、当分の間は修正されない可能性があります。
そのため、display: grid, place-items: center, aspect-ratioが使用されている場合は、Safariで表示崩れが発生しないようにwidthを必ず指定してください。