user2915010
user2915010

Reputation: 47

Tailwind images going are not contained in containers

I am struggling to make my images fill or fit their containers. I want them to take all available of the view and not beyond the view.

<div class="flex h-screen max-h-screen border-2">
  <div class="w-1/2">
    <div class="h-12 bg-red-100">here</div>
    <div class="flex-1 border-2 border-red-200">
      <img class="h-full object-contain" src="https://picsum.photos/2000/4000" alt="first image" />
    </div>
  </div>
  <div class="w-1/2">
    <div class="h-12 bg-red-100">here</div>
    <div class="flex-1 h-full border-2 border-red-200">
      <img class="object-fill" src="https://picsum.photos/200/300" alt="test" />
    </div>
  </div>
</div>

https://play.tailwindcss.com/6GMm4k4vxU

THX

Upvotes: 1

Views: 1000

Answers (1)

ChenBr
ChenBr

Reputation: 2612

You can remove the images' containers and apply w-full and h-full to both. Then, apply overflow-hidden to hide the images' overflowing parts.

Of course, the second image (https://picsum.photos/200/300) will always be blurry because we're scaling it up quite a bit.

You can also remove the max-h-screen because we already set a constant height to the screen, which is 100vh (h-screen).

<div class="flex h-screen border-2 border-red-600">
  <div class="flex w-1/2 flex-col">
    <div class="min-h-12 bg-red-100">here</div>
    <img class="h-full w-full overflow-hidden" src="https://picsum.photos/2000/4000" alt="test" />
  </div>
  <div class="flex w-1/2 flex-col">
    <div class="min-h-12 bg-red-100">here</div>
    <img class="h-full w-full overflow-hidden" src="https://picsum.photos/200/300" alt="test" />
  </div>
</div>

Tailwind-play


The above method might stretch your images. Here's another solution that should take care of it:

Remove the images thoroughly. We're going to show them as a background image. We'll start by adding the background's images to tailwind.config:

module.exports = {
  theme: {
    extend: {
      backgroundImage: {
        '1000': "url('https://picsum.photos/1000/1000')",
        '1200': "url('https://picsum.photos/1200/1200')",
      }
    }
  }
}

You can read about this method here. You can also read about configuring the default theme here.

We'll then change the structure of the images by splitting our view into two containers (w-1/2 each). Each container will have an image as a background applied using the custom background we created (bg-1000 and bg-1200). Each container also has a div inside it. This div is entirely optional.

<div class="flex h-screen border-2 border-red-600">
  <div class="w-1/2 bg-1200">
    <div class="h-12 bg-red-100">here</div>
  </div>
  <div class="w-1/2 bg-1000">
    <div class="h-12 bg-red-100">here</div>
  </div>
</div>

Tailwind-play

Upvotes: 2

Related Questions