85
62

More than 5 years have passed since last update.

imgだけどサイズをbackground-size: cover;みたいにしたい

Posted at

imgをcover化させる!

スライダーとかでバックグラウンドじゃなく、imgタグで入れたいけど、画面いっぱいにやりたい!
ってときに役に立つかと思います。

今回の例ではスライドを画面いっぱいにするので、クラス名はそんな感じで

index.html
<div class="slide">
  <img src="sample.png" alt="sample" width="150" height="100">
</div>
cover.css
.slide {
  position: relative;
  height: 100vh;
}
.slide img {
  position: absolute;
  top: 0;
  left: 0;
  width: auto;
  height: auto;
  min-width: 100%;
  min-height: 100%;
  max-width: inherit;
}

imgタグの親にposition: relativeを入れて、imgタグにもろもろを入れていく感じになります。

これでimgタグがbackground-size: cover;と同じような感じになります。

object-fit

IEを対応にしない場合はobject-fitというのが使えます

cover2.css
.slide img {
  object-fit: cover;
  width: 100%;
  height: 100%
}

モバイル対応だけの場合はこちらでもいいかもしれませんね!

85
62
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
85
62