- Instant help with your CSS coding problems

Stretch children to fill horizontally

Question:
How to stretch children to fill horizontally?
Answer:
<div class="flex w-1/6 bg-sky-50 border border-sky-500 p-2">
    <div class="flex grow p-2 border border-amber-500 bg-amber-50 mr-2">1</div>
    <div class="flex grow p-2 border border-amber-500 bg-amber-50 mr-2">2</div>
    <div class="flex grow p-2 border border-amber-500 bg-amber-50">3</div>
</div>
Description:

If you put several children's items in a flex container, each child will only take up as much space as it needs. This means that with a wide container, there is empty space in the container.

For example the following code:

<div class="flex w-1/6 bg-sky-50 border border-sky-500 p-2">
    <div class="flex p-2 border border-amber-500 bg-amber-50 mr-2">1</div>
    <div class="flex p-2 border border-amber-500 bg-amber-50 mr-2">2</div>
    <div class="flex p-2 border border-amber-500 bg-amber-50">3</div>
</div>

will result in this output:

Default fill without stretch

If you want the child items to completely fill the available space so each child item has the same width, use the flex-grow property set to 1 . In TailwindCSS, use the grow utility class to do this as you can see here:

<div class="flex w-1/6 bg-sky-50 border border-sky-500 p-2">
    <div class="flex grow p-2 border border-amber-500 bg-amber-50 mr-2">1</div>
    <div class="flex grow p-2 border border-amber-500 bg-amber-50 mr-2">2</div>
    <div class="flex grow p-2 border border-amber-500 bg-amber-50">3</div>
</div>

And the result is: 

Stretch children to fill parent


Alternatively, you can use the w-full class to set the width property to 100% for all elements. In this case, the child elements will have the same width even if one element has much more content.

<div class="flex w-1/6 bg-sky-50 border border-sky-500 p-2">
    <div class="p-2 w-full border border-amber-500 bg-amber-50 mr-2">1</div>
    <div class="p-2 w-full border border-amber-500 bg-amber-50 mr-2">
        Lorem ipsum dolor sit amet consectetur adipisicing elit.
    </div>
    <div class="p-2 w-full border border-amber-500 bg-amber-50">3</div>
</div>

In this case the result is:

Stretch equally with different content

Share "How to stretch children to fill horizontally?"
Interesting things
OpanAi's ChatGPT