Ray Purchase
Ray Purchase

Reputation: 762

How to stop a child div expanding to fit the width of its parent in Flexbox with Tailwind

<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"/>
<div class="flex flex-row space-x-2">
    <div class="h-10 w-10 bg-gray-200 rounded-full"></div>
    <div class="flex flex-col space-y-1">
        <div class="flex flex-col p-2 bg-gray-200">
            <span class="text-xs font-semibold tracking-tight">Username</span>
            <p class="text-sm font-base">comment</p>
        </div>
        <div class="flex flex-row pl-2 space-x-1">
            <span class="text-xs font-bold">Like</span>
            <button class="text-xs font-bold hover:text-blue-600">Reply</button>
            <span class="text-xs font-bold">October 24</span>
        </div>
    </div>
</div>

I have a simple problem but it's driving me crazy trying to resolve it. I have a simple Comment component. The question is, how do I stop the div containing the username and comment expanding (as it is) to the width of its parent? The rectangle grey div should only be the width of its contents, ie 'comment', not the width of the content below it which is determining the size of the parent

example of problem

I have a sandbox here: https://play.tailwindcss.com/nEisDNFj4v

And this is the sample code:

<div class="flex flex-row space-x-2">
    <div class="h-10 w-10 bg-gray-200 rounded-full"></div>
    <div class="flex flex-col space-y-1">
        <div class="flex flex-col p-2 bg-gray-200">
            <span class="text-xs font-semibold tracking-tight">Username</span>
            <p class="text-sm font-base">comment</p>
        </div>
        <div class="flex flex-row pl-2 space-x-1">
            <span class="text-xs font-bold">Like</span>
            <button class="text-xs font-bold hover:text-blue-600">Reply</button>
            <span class="text-xs font-bold">October 24</span>
        </div>
     </div>
 </div>

Many thanks, Matt

Upvotes: 0

Views: 5345

Answers (2)

tromgy
tromgy

Reputation: 5853

There's even simpler way:

Add items-start class to your third div:

<div class="flex flex-col items-start space-y-1">

Here's the link: https://play.tailwindcss.com/piFbOgE3I0

Upvotes: 4

Si8
Si8

Reputation: 9235

You can set .p-2 to align-self: flex-start;

Link: https://play.tailwindcss.com/n63l2rncAa?file=css

Upvotes: 0

Related Questions