LoginSignup
14
13

More than 5 years have passed since last update.

CSS 画像を中央配置

Last updated at Posted at 2016-02-26

画像の上下中央を揃えるのによくやるやつ

上下中央を揃えるのに、vertical-alignを指定したり
block要素にはvertical-alignきかないのでdisplay:table-cellを指定したり
というやり方はなんかイマイチなので

imgを中央配置したいとき

画像自体を調整するのが一番だけど、結構手間だし
サイズが微妙に違う画像に同じスタイルあてたいときとか
2.png

css
p{
    position: relative;
    width: 100px;
    height: 100px;

}
img{
    position: absolute;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
    margin: auto;
}

imgが親のblockよりも大きい場合

アイコンなどで余白が大きかったり
画像の中央しか表示させる必要がないとき
1.png

css
p{
    position: relative;
    overflow: hidden;
    width: 50px;
    height: 50px;

}
img{
    position: absolute;
    top: -50px;
    bottom: -50px;
    right: -50px;
    left: -50px;
    margin: auto;
}

親要素をoverflow:hidden
imgのpositionの値をネガティブにする(必要十分な大きさ)

こうすることで四隅のマージンが均等に調整され
画像を中央に配置できる

14
13
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
14
13