padam thapa
padam thapa

Reputation: 1477

Image Aspect Fill Mode: CSS

I am an iOS developer. We have aspect fill property on of imageview. This property lets image fill the target viewport or container but keeping aspect ratio.

Now fill works in certain way which I couldn't achieve using pure css. I am gonna write down the code below. And explaining my need is struggle to phrase it in english so please try to endure it and have patience. So here it is:

Aspect Fill: This only fills with scale factor that is required. For example: If image is bigger than viewport size then image will scale down maintaining aspect ratio until it gets smaller than viewport else it will be "fit" effect. It has to fill the viewport. Extra part that is out of viewport's bounds will be clipped off.

If image is smaller than viewport then image will scale up maintaining aspect ratio until it just fills the viewport. Extra part that is out of viewport's bounds will be clipped off.

Scale factor of fill is important. I hope I explained my need. After trying to learn around the web to achieve I came up with below code. This code doesn't fill the way I want. It maintains aspect ratio but fills with 100% zoom or scale.

.page-container, .page {
  width: 320px;
  height: 480px;
}

.page {                     
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.page-image {
  flex-shrink: 0;
  min-width: 100%;
  min-height: 100%;
}
<div class="page-container">
  <div class="page">
     <img class="page-image" src="https://images.unsplash.com/photo-1495974887311-a817001ebd74" alt="">
  </div>
</div>

You can look at that original image in unsplash link. You can test on smaller image: https://upload.wikimedia.org/wikipedia/commons/5/50/Salta-VallesCalchaquies-P3140151.JPG

Can this mode be achieved in pure css or Do i need javascript to manipulate the new size for every image that aspect-fills the viewport according to my requirement?

Upvotes: 0

Views: 3110

Answers (1)

Zeronull
Zeronull

Reputation: 261

You can use object-fit: cover; in your image-class.

You also need to add width and height to your image. (Note: It doesn't work on Internet Explorer but you could add a polyfill like this! to make it work there as well).

Here's the example, based on your code:

.page-container, .page {
  width: 320px;
  height: 480px;
}

.page {                     
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.page-image {
  flex-shrink: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div class="page-container">
  <div class="page">
     <img class="page-image" src="https://images.unsplash.com/photo-1495974887311-a817001ebd74" alt="">
  </div>
</div>

Upvotes: 3

Related Questions