LoginSignup
1
3

More than 1 year has passed since last update.

画像の表示サイズを変形させずに揃える方法

Last updated at Posted at 2021-07-31

解決したい問題

Railsでレシピを投稿できるアプリケーションを作成中、360×260の大きさでレシピ画像を表示したかったのですが、イメージタグにサイズ指定をしただけだと、縦長の画像をアップロードした際、画像が変形してしまいました。

xxxx.erb
<%= attachment_image_tag @recipe, :recipe_image, size: '360x260', format:'jpeg' %>

※画像アップロードにはrefileを使用しています

この画像をアップロードすると↓           変形してしまう↓
       

この問題を解決してくれる便利なCSSプロパティがあったのでご紹介します!

解決方法

object-fitプロパティを使う!

xxxx.erb
<div class="img-container">
  <%= attachment_image_tag @recipe, :recipe_image, format:'jpeg' %>
</div>
application.css
.img-container {
  width: 360px;
  height: 260px;
}
.img-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

画像の幅と高さを指定して、object-fit: cover;を追加するだけで中央でトリミングされました!

object-fitプロパティではcover以外に、縦横比を保持してボックスに収まるようにリサイズしてくれるcontainや、リサイズせずにそのまま画像を表示するnoneなどの値も使えます。
希望の表示形式に合わせて使い分けしてみてください!

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