WebMasterCampus
WEB DEVELOPER Resources

CSS Object Fit Property Resized an Image to Fit Inside a Container

Learn how to use CSS Object Fit Property Resized an Image to Fit Inside a Container


CSS Object Fit Property Resized an Image

The object-fit CSS property resize image, center (both vertically and horizontally) and than crop it to fit inside container. It’s the best solution for an or element.

CSS object-fit possible values

fill | contain | cover | none | scale-down

<!DOCTYPE html>
<html>
<head>  
  <meta name="viewport" content="width=device-width">
  <style>
    .centered-and-cropped {
      object-fit:cover;
    }
  </style>
</head>
<body>
<h1>original</h1>
<img height="200" src="https://images.unsplash.com/photo-1517849845537-4d257902454a?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=675&q=80" alt="Dog">
    
<h1>object-fit: cover</h1>
<img class="centered-and-cropped" width="300" height="300" 
style="border-radius:50%" src="https://images.unsplash.com/photo-1517849845537-4d257902454a?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=675&q=80" alt="Dog">
  
</body>
</html>
Created with love and passion.