image-contain not fitting portrait image in parent container

13 views Asked by At

When the image is of portrait orientation, it will show with the width as the width of the container, even though it is taller than that and i am using object-contain in my tailwind classes. I am using Sveltekit, but most of the code is just plain HTML with tailwind

I have looked on stackoverflow and asked Copilot and Phind and cannot find an answer. I have used an {#if} block with calculations in the script tag up the top, where I check whether the width is more than the height:

{#if naturalWidth > naturalHeight}
                    <img src={$overlayImage} alt="overlay image" class="w-full h-auto object-contain justify-center" on:load={imageLoaded} />
                {:else}
                    <img src={$overlayImage} alt="overlay image" class="w-auto h-full object-contain justify-center" on:load={imageLoaded} />
                {/if}

...but this does not work

My current code is the following:

{#if $isOverlayOpen}
<div class="fixed top-0 left-0 w-screen h-screen flex items-center justify-center z-50">
    <div class="w-4/5 h-4/5 min-w-2 min-h-2 bg-black opacity-100 text-white rounded-lg overflow-hidden box-sizing: border-box;">
        <div class="grid grid-cols-4 border-0 gap-0">
            <div class="col-span-3 min-h-full border-0 items-center justify-center place-items-center">
                <img src="https://unsplash.com/photos/a-forest-filled-with-lots-of-tall-pine-trees-CRFqapQ0P0U" alt="overlay image" class="object-contain min-h-0" />
            </div>
            <div class="min-h-full border-0">
                <button on:click={() => isOverlayOpen.set(false)}>Close overlay</button>
                <h2>Ordering options go here</h2>
            </div>
        </div>
    </div>
</div>
{/if}

I'm wondering whether this is wrong code or something weird with tailwind? It's what multiple articles and AIs have told me to do but it still does not work for me

0

There are 0 answers