cssimagetailwind-css

Tailwind ObjectFit directives (like object-cover, object-fit, etc.) have no effect


Below is MWE. None of the directives have any effect on how the image span covers the parent container:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tailwind Object Cover Example</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 flex items-center justify-center min-h-screen">
    <div class="w-64 h-64 overflow-hidden rounded-lg shadow-lg bg-green-100">
      <img src="https://via.placeholder.com/400" alt="Example Image" class="object-fill
                                        w-6 h-6">
    </div>
</body>
</html>


Solution

  • As per the MDN documentation:

    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.

    The "content" mentioned above means the image or the video itself, and the container means the <img> or <video> tag. The object-fit properties do not affect the sizing of the tag, but the content "inside" it.

    Here is an example to demonstrate this:

    <script src="https://cdn.tailwindcss.com/3.4.5"></script>
    
    <img src="https://picsum.photos/400" class="object-fill w-96 h-40">
    <img src="https://picsum.photos/400" class="object-fill w-40 h-96">
    <img src="https://picsum.photos/400" class="object-fill w-40 h-40">

    Notice the image itself is stretched to fill the <img> tag's dimensions.

    Back to your problem. Since the parent element has defined width and height properties, you can apply width: 100%; height: 100% to fill the parent container:

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Tailwind Object Cover Example</title>
      <script src="https://cdn.tailwindcss.com/3.4.5"></script>
    </head>
    
    <body class="bg-gray-100 flex items-center justify-center min-h-screen">
      <div class="w-64 h-64 overflow-hidden rounded-lg shadow-lg bg-green-100">
        <img src="https://via.placeholder.com/400" alt="Example Image" class="object-fill size-full">
      </div>
    </body>
    
    </html>