LoginSignup
4
3

More than 5 years have passed since last update.

【CSS】画像をいい感じに(中央に、丸く)表示する

Last updated at Posted at 2017-05-27

Rails勉強中ですが、今日はCSSで画像をいい感じに表示してみたいと思います。(息抜き)

そのまま

image.html
<div class="box">
  <img src="image.jpg" class="image">
</div>
style.css
.box {
  width: 300px;
  height: 300px;
  position: relative;
}
.image {
  position: absolute;
}

"box"という箱の中に"image"という画像を配置しています。
"box"のサイズを300px角としていますが、そのままだと画像の方が大きくなっています。
image.png

はみ出た部分をカット

親要素である""box"にoverflowプロパティを追加します。

style.css
.box {
  width: 300px;
  height: 300px;
  position: relative;
  overflow: hidden; /*追加*/
}
.image {
  position: absolute;
}

hiddenとするとはみ出た部分がカットできました。でも空しか写っていません。
image.png

画像を中央に移動

"box"の中心に画像の中心を持っていきたいと思います。

style.css
.box {
  width: 300px;
  height: 300px;
  position: relative;
  overflow: hidden;
}
.image {
  position: absolute;
  top: 50%; /*追加*/
  left: 50%; /*追加*/
}

まずは、画像のpositionをabsoluteで左上から50%で指定。これで画像の起点(左上)が"box"の中心に移動します。(ここでの50%は"box"の半分)
image.png

style.css
.box {
  width: 300px;
  height: 300px;
  position: relative;
  overflow: hidden;
}
.image {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); /*追加*/
}

続いて、transformのtranslateで画像をXY方向ともに-50%移動します。(ここでの50%は画像の半分)
これで"box"の中心に画像の中心を持っていくことができました。
image.png

丸くする

最後におまけとして、"box"を丸くします。

style.css
.box {
  width: 300px;
  height: 300px;
  position: relative;
  overflow: hidden;
  border-radius: 300px; /*追加*/
}
.image {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -40%); /*調整*/
}

border-radiusプロパティの値をwidth,heightと同じにすると円となります。位置を調整して完成。
image.png

ありがとうございました。

4
3
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
4
3