Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scaling, centering and cropping image with object-fit and object-position

Tags:

html

css

I would like to take an aleatory image and having it scale up / down to use the whole space of the parent div, while maintaining its original proportions. I expect the image to be cropped (it's ok, as long it's centered both vertically and horizontally).

I've tried this code:

<div class="container" style="width: 800px">
  <div class="row">
    <div style="
          height:340px; 
          width: 100%; 
          overflow: hidden;
          border: 3px solid red;
          ">
      <img src="http://via.placeholder.com/500x500" style="
            object-position: center;
            object-fit: cover;
            ">
    </div>
  </div>
</div>

And here's the result: Screenshot of result of original code. A div with a red outline as a photo of the Rolling Stones. The photo is aligned to the left and does not fill the div width wise. The background image can be seen through the div where the image does not fill it.

Why isn't it scaling up, centering and cropping the image?

like image 391
João Otero Avatar asked Jul 21 '17 03:07

João Otero


People also ask

What is object-fit?

The object-fit CSS property sets how the content of a replaced element, such as an <img> or <video> , should be resized to fit its container. You can alter the alignment of the replaced element's content object within the element's box using the object-position property.

What is object-position in CSS?

The object-position CSS property specifies the alignment of the selected replaced element's contents within the element's box. Areas of the box which aren't covered by the replaced element's object will show the element's background.


1 Answers

Give the image some dimensions (compare to the second image, which has no defined dimensions)

<div class="container" style="width: 800px">
  <div class="row">
    <div style="
      height:150px; 
      width: 250px; 
      overflow: hidden;
      border: 3px solid red;
      ">
      <img src="http://placekitten.com/400/200" style="
        width:100%;
        height:100%;
        object-position: center;
        object-fit: cover;
        ">
    </div>
  </div>
  <br>
  <div class="row">
    <div style="
      height:150px; 
      width: 250px; 
      overflow: hidden;
      border: 3px solid red;
      ">
      <img src="http://placekitten.com/400/200" style="
        object-position: center;
        object-fit: cover;
        ">
    </div>
  </div>
</div>
like image 97
sideroxylon Avatar answered Sep 18 '22 21:09

sideroxylon