Search code examples
htmlcssflexboxweb-frontend

Flexbox does not give equal width to all elements even when flex-shrink and flex-grow set to 0


I have a div container inside an article.

<article>
        <div class="flex">
            <article class="img"><img src="Demo.webp" alt="Demo" height="250px" /></article>
            <div style="background-color: red;"></div>
            <section style="background-color: blue;"></section>
        </div>
        <button class="add-to-cart">Add To Cart</button>
</article>

This is the CSS to my flex container:

.flex {
    display: flex;
    gap: 40px;
    flex: 0 0 0;
}

According to my understanding, if I set flex-shrink and flex-grow to 0 (which I have done using the flex property) then each of the child elements of this flexbox should have equal width. When inspecting the web page however, they have a width of 0 (therefore it cannot be seen).

The browser gives the following error:

The display: block property on the parent element prevents flex from having an effect. Try setting the display: block property on the parent to display: flex.

Please help me by explaining the error and the solution.

Similar questions have been asked on Stack Overflow in the past, but I could not find any with my exact same situation. In my case the flex property (flex-basis, flex-grow, flex-shrink) are not working as described in other questions.


Solution

  • flex-shrink and/or flex-grow properties are not inherited by children. They should not be applied to the parent but to the element itself.

    This should be working :

     .flex {
        display: flex;
        gap: 40px;
    }
    
    .flex > * {
        display: flex;
        flex : 1;
    }
    

    .flex > * targets all direct children of your .flex elements.

    flex: 1 will make all your elements have the same width see : https://developer.mozilla.org/fr/docs/Web/CSS/flex

    Hope that helps !