Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want an image to fill the 100% of its container's width, and I want it to have a max-heigth property set to it, all this keeping the aspect ratio but allowing to lose any part of the image.

img {
   max-height:200px;
   width:100%;
}

I know a similar thing can be done with background-size property but i want to make this to an inline <img> tag.

Any idea of how could i achieve this using CSS? or javascript?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
558 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can try CSS3 object-fit, and see browser support tables.

CSS3 object-fit/object-position Method of specifying how an object (image or video) should fit inside its box. object-fit options include "contain" (fit according to aspect ratio), "fill" (stretches object to fill) and "cover" (overflows box but maintains ratio), where object-position allows the object to be repositioned like background-image does.

JSFIDDLE DEMO

.container {
  width: 200px; /*any size*/
  height: 200px; /*any size*/
}

.object-fit-cover {
  width: 100%;
  height: 100%;
  object-fit: cover; /*magic*/
}
<div class="container">
  <img class="object-fit-cover" src="https://i.stack.imgur.com/UJ3pb.jpg">
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...