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

Time:10-24

<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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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

CodePudding user response:

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

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

CodePudding user response:

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

  • Related