LoginSignup
6

More than 5 years have passed since last update.

htmlでaspect to fill, aspect to fitを実現する

Posted at

Aspect to fill, Aspect to fitとは

carrierwaveだとresize_to_fill, resize_to_fitに対応。
どちらも画像のアスペクト比を保つが、矩形への収め方が異なる。
わりと使用頻度は多いと思うのでヘルパーとかを用意すると楽です。

元画像

矩形が600x480のとき

Aspect to fitの場合

画像がすべて収まるように配置される。

Aspect to fillの場合

領域をすべて埋めるように画像が拡大されて配置される。

cssで実現するには?

画像をbackground-imageで指定したあと、background-sizeの値をcontaincoverにする。containはFillに、coverはFitに対応します。

サンプル(Railsの場合)

background imageを指定するのが面倒なのでビューヘルパーを定義しておく。

app/helpers/image_helper.rb
module ImageHelper
  def background_image_tag(path, html_options = {})
    html_options = html_options.merge(
      style: "background-image: url('#{path}')"
    )
    content_tag 'span', '', html_options
  end
end

cssをmixinにしておく。

@mixin aspectToFit
  background-size: contain
  background-repeat: no-repeat
  background-position: center center
  background-color: black

@mixin aspectToFill
  background-size: cover
  background-repeat: no-repeat
  background-position: center center

あとはviewでタグを呼び出して、mixinを適応する。

.productImage
  = background_image_tag photo.picture.url, class: 'photo'
.photo
  @include aspectToFill

注意点

  • background-sizeはIE~8,9あたりでは動かない気がするので注意してください。

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
6