Safariはplace-items:centerで上下中央揃えできないバグがある

CSSのplace-items:centerで上下中央揃え

Webサイトを制作していると、以下のように特定の親要素内の子要素を上下中央揃えにしたいことがあります。

HTML
<div class="content">
  <div class="sample">sample</div>
</div>
sample

このような配置は最近だと「display: grid」と「place-items: center;」を使用して作成されることが多いです。

CSS
.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つのプロパティを指定しても上下中央揃えになりません。

HTML
<div class="box">
  <div class="sample">sample</div>
</div>
CSS
.box {
  display: grid;
  place-items: center;
  aspect-ratio: 4 / 1;
  border: 1px solid #CCC;
}

.sample {
  padding: 10px;
  background: skyblue;
}
sample

※ このHTML&CSSだとSafariだと下図のように上下中央揃えになりません。

Safariはplace-items:centerで上下中央揃えできないバグがある

Safariのバグの解決方法

この問題を解決するには、aspect-ratioを指定している要素にwidthを指定します。

Safariで「aspect-ratio: 4 / 1」だけ指定されていると、高さを計算して認識できず、「place-items: center」が効きません。

「align-content: center」などでも直りますが、「place-items: center」を指定しているので、widthで直したほうが良いでしょう。

HTML
<div class="box-fix">
  <div class="sample">sample</div>
</div>
CSS
.box-fix {
  display: grid;
  place-items: center;
  aspect-ratio: 4 / 1;
  width: 100%;
  border: 1px solid #CCC;
}

.sample {
  padding: 10px;
  background: skyblue;
}
sample

結構前から発生しているバグなのですが、2024年4月現在の最新バージョンSafari 17.4.1でも発生しているので、当分の間は修正されない可能性があります。

そのため、display: grid, place-items: center, aspect-ratioが使用されている場合は、Safariで表示崩れが発生しないようにwidthを必ず指定してください。