Search code examples
htmlcsstailwind-css

Tailwind CSS resize column width


I'm trying, just for exercise, to make a simple card that looks like a Whatsapp chat preview. I'm using tailwind css and a grid layout to achieve it. Here is my code:

<div class="grid grid-cols-4 w-96 bg-zinc-800 rounded-md">
<div class="shrink-0 p-3 border-red-800 max-w-fit h-20 border">
    <img src="./assets/placeholder.png" alt="" class="max-h-full rounded-full">
</div>
<div class="p-3 col-span-2 font-helvetica border-red-800 border">
    <h1 class="text-neutral-100">Andrea Militano</h1>
    <div class="flex text-neutral-400">
        <fa-icon [icon]="faCheck" class=""></fa-icon>
        <fa-icon [icon]="faCheck" class="-translate-x-2"></fa-icon>
        <p class="text-sm truncate -translate-x-1">Contenuto del messaggio, Contenuto del messaggio, Contenuto del messaggio</p>
    </div>
</div>
<div class="border-red-800 justify-self-end p-3 border">
    <p class="text-neutral-400 text-sm">21.23</p>
</div>

and this is the result: Grid Layout

How can I to to let the second column to grab all the space left from the other two columns? I thought that with a flex layout it was easier, but I struggle to make the last div end within the parent div border. This is the flex variant:

<div class="flex w-96 bg-zinc-800 rounded-md">
<div class="shrink-0 p-3 border-red-800 max-w-fit h-20 border">
    <img src="./assets/placeholder.png" alt="" class="max-h-full rounded-full">
</div>
<div class="p-3 font-helvetica border-red-800 border max-w-[65%]">
    <h1 class="text-neutral-100">Andrea Militano</h1>
        <div class="flex text-neutral-400">
            <fa-icon [icon]="faCheck" class=""></fa-icon>
            <fa-icon [icon]="faCheck" class="-translate-x-2"></fa-icon>
            <p class="text-sm truncate">Message content</p>
        </div>
</div>
<div class="border-red-800 p-3 border">
    <p class="text-neutral-400 text-sm">21.23</p>
</div>
With the following result:

Flex Layout

Any suggestion?


Solution

  • You can do so by adding flex-1 to fill the empty space and adding overflow-hidden to fix text overflow from the parent.

    <div class="flex w-96 gap-3 rounded-md bg-zinc-800">
      <div class="h-20 max-w-fit shrink-0 border border-red-800 p-3">
        <img src="https://i.pravatar.cc/150?img=3" alt="" class="max-h-full rounded-full" />
      </div>
      <div class="flex-1 font-helvetica border border-red-800 p-3 overflow-hidden">
        <h1 class="text-neutral-100">Andrea Militano</h1>
        <div class="flex text-neutral-400">
          <fa-icon [icon]="faCheck" class=""></fa-icon>
          <fa-icon [icon]="faCheck" class="-translate-x-2"></fa-icon>
          <p class="truncate text-wrap text-sm">Message content</p>
        </div>
      </div>
      <div class="border border-red-800 p-3">
        <p class="text-sm text-neutral-400">21.23</p>
      </div>
    </div>