LoginSignup
5
2

More than 5 years have passed since last update.

chrome系ブラウザで、flexboxによる上下左右中央指定がずれる

Last updated at Posted at 2016-08-29

よく知られている、flexboxを利用した上下左右のセンタリング

.border
  .chip
.border {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 110px;
  height: 110px;
  background-color: aqua;
  margin-bottom: 50px;
}

.chip {
  width: 100px;
  height: 100px;
  background-color: red;
}

このように書くと、justify-content: center;align-items: center;によって、子要素が上下左右中央になるのはよく知られたテクニックだと思います。
スクリーンショット 2016-08-29 18.26.23.png

子要素(または親要素)の大きさが奇数になる時に、chrome系ブラウザで中央からずれる

こういうスタイルを適用するとどうでしょうか。上のスタイルの、widthheightのみを変更したものです。

.border {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 20px;
  height: 20px;
  background-color: aqua;
  margin-bottom: 50px;
}

.chip {
  width: 17px;
  height: 17px;
  background-color: red;
}

ちなみにcodepenに作成したのがこちらになります。

chrome 52.0.2743.116 (OSX 64-bit)

スクリーンショット 2016-08-29 18.37.52.png

chrome 52.0.2743.116 m (Windows10 64-bit)

キャプチャ.PNG

chromium 48.0.2559.0 (OSX 64-bit)

スクリーンショット 2016-08-29 18.40.45.png

vivaldi 1.3.551.38 (OSX Stable channel)

スクリーンショット 2016-08-29 18.41.41.png

firefox 47.0 (OSX)

スクリーンショット 2016-08-29 18.38.50.png

safari 9.1.2 (11601.7.7)

スクリーンショット 2016-08-29 18.39.33.png

IE11 11.545.10586.0

キャプチャ.PNG

Edge 25.10586.0.0

キャプチャ.PNG

センタリングされない!!!

正確にはどのような問題か

様々な値を設定して確かめましたが、どうやら「親要素の大きさが偶数(奇数)のとき、子要素の大きさが奇数(偶数)のとき、chrome系ブラウザでセンタリングされない」ことがわかりました。親と子との奇偶が一致していないとダメなようです。1

ワークアラウンド

親と子の奇偶を揃えてやりましょう。

これは親が23px四方、子が19px四方、ブラウザはchromiumの場合です。
スクリーンショット 2016-08-29 18.49.59.png


  1. 親要素、子要素共に正方形の場合しか試していません。 

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2