Help us understand the problem. What is going on with this article?

CSS 画像を中央配置

More than 3 years have passed since last update.

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

上下中央を揃えるのに、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の値をネガティブにする(必要十分な大きさ)

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした