LoginSignup
1
4

More than 5 years have passed since last update.

CSS だけで画像の切り抜きをうまくやる

Last updated at Posted at 2017-06-20

CSS3 object-fit

概要は下記のページを参考。

1行追加でOK!CSSだけで画像をトリミングできる「object-fit」プロパティー
http://www.webcreatorbox.com/tech/object-fit/

実装したいこと

枠内に画像をうまく納める。
切り抜き位置を中央にしておきつつ、アニメーションで見える範囲を移動させる。

前提

  • 画像の縦横幅がバラバラ
  • 縦横の比率もバラバラで、横長も縦長も混在
  • スマホ前提でレイアウトは1つ

レイヤー

  • div
    • img

CSS

div

width: 60%;
max-height: 110px;
overflow: hidden;

img

width: 60%;
max-height: 110px;
object-fit:cover;

ポイント

object-fit を指定した img に、幅・高さも指定しないと object-fit:cover が効かない。
div のサイズは外枠レイアウト用の幅高さ指定、img は画像の切り抜きサイズ、という考え方かな。

確認

画像が切れていても、 img にサイズ指定がない場合は、 div の overflow で見切れているだけの場合がある。
その場合は object-position が効かないので切り抜き位置が変えられない。
object-position が効いて、切り抜き位置を変えられるようならOK。

ex.
img

width: 60%;
max-height: 110px;
object-fit:cover;
object-position: 0% 0% ;

アニメーション

position を @keyframes に書いて、 img の animation で指定する。

前提

  • スマホWeb
1
4
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
4