DEV Community

Tsuyoshi Tokuda
Tsuyoshi Tokuda

Posted on

2 1

background-size を使って画像を適切な枠に収めるのは object-fit を使ったらとても簡単だった

CSS のプロパティに object-fit というのがあるのは知っていたけど便利だと思ったので調べてみた。

アイテムが複数カラムで一覧上にレイアウトされている場合、画像サイズの違いから段違いにならないようにするために画像が表示されている部分の枠のサイズを固定していることが多いと思う。
固定した枠に対して画像をアスペクト比を保ったまま、枠サイズに隙間が出ないようにしたり、隙間が出ても画像の切り捨て部分がないように伸縮させて表示させたりする。

background-size を使った方法

今までは以下のようなマークアップで表示させていた。img 要素で一般的に表示する方法だと、JavaScript で画像ダウンロードしたものを枠に対してサイズ調整をしてはめていかなければいけません。

<ul class="items">
  <li class="item">
    <a>
      <img
        class="item__img"
        src="<base64エンコードした1pxの透明なダミー画像>"
        style="background-image: url(<画像URL>);" />
    </a>
  </li>
</ul>
Enter fullscreen mode Exit fullscreen mode
.item__img {
  background-position: center center;
  background-repeat: no-repeat;
  background-size: contain;
  height: 200px;
  width: 200px;
}
Enter fullscreen mode Exit fullscreen mode

このように、HTML では img 要素の src 属性にbase64エンコードした1pxの透明なダミー画像で表示させて、style 属性で background-image を指定する。次に CSS で background-size: contain; を指定することで、img 要素で指定した背景画像に対してサイズの伸縮をさせているので、手数としては多すぎる。

object-fit を使った方法

object-fit を使う場合は、もっと簡単になる。

<ul class="items">
  <li class="item">
    <a>
      <img
        class="item__img"
        src="<画像URL>" />
    </a>
  </li>
</ul>
Enter fullscreen mode Exit fullscreen mode
.item__img {
  height: 200px;
  object-fit: contain;
  width: 200px;
}
Enter fullscreen mode Exit fullscreen mode

img 要素の CSS のクラスで object-fit: contain; と宣言すればいい。
このような宣言を書くことで、img 要素の中身(この場合は画像)がどのように枠に対して伸縮されて表示されるかを指定することができる。

まとめ

すごく便利なプロパティだが、Internet Explorerは使えないので、採用する場合はターゲットブラウザを確認する必要がある。

また、今回用いたコードはGithubで公開している。

参照

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay