8

I'm trying to use flex to create flex-items of same width, but they keep changing width depending on number of children in flex-item

fiddle

As you can see, the right green container is much smaller, even though both have flex-grow:1

How can I fix this? Thanks!

span {
    display: inline-block;
    width: 10px;
    height: 30px;
    border: 1px solid red;
}
.container {
    display: flex;
    display: -webkit-flex;
    border: 1px solid blue;
    width: 200px; 
    padding: 2px;

}
.item {
    flex-grow: 1;
    -webkit-flex-grow: 1;
    border: 1px solid green;
}
hippietrail
  • 15,848
  • 18
  • 99
  • 158
skyisred
  • 6,855
  • 6
  • 37
  • 54

5 Answers5

8

using flex:1 instead of flex-grow:1 seems to fix the issue.

skyisred
  • 6,855
  • 6
  • 37
  • 54
4

This is because flex-basis defaults to auto, which factors in the width of the element. To keep your elements the same with, you need to explicitly set flex-basis: 0:

.item {
  flex-basis: 0;
  flex-grow: 1;
}

See: https://jsfiddle.net/Wexcode/Lgqhcr07/

Wex
  • 15,539
  • 10
  • 64
  • 107
2

if you don't specify a width to your flex-item (.item) they width is "auto" and they will adjust to its children element (in your case 'span').

Most implementation of flexboxes have 'width' specified for their items.

ThiagoPXP
  • 5,362
  • 3
  • 31
  • 44
0

I think this should be the solution...

span {
    flex-grow: 1;
    height: 30px;
    border: 1px solid red;
}
.container {
    display: flex;
    display: -webkit-flex;
    border: 1px solid blue;
    width: 200px; 
    padding: 2px;

}
.item {
    flex-grow: 1;
    display: inherit;
    -webkit-flex-grow: 1;
    border: 1px solid green;
}
<div class="container">
    <div class="item">
        <span></span>
        <span></span>
        <span></span>

    </div>
    <div class="item">
        <span></span>
    </div>
</div>
deadkff01
  • 41
  • 3
  • spans inside should be of specific width. When I remove flex-grow from spans, the problem comes back – skyisred Feb 24 '15 at 06:35
0

or use flex-basis: 100%; (you can remove flex-grow: 1;)

It's very well explained at http://www.w3.org/TR/css3-flexbox/#flex-basis:

flex-basis
This component, which takes the same values as the ‘width’ property, sets the ‘flex-basis’ longhand and specifies the flex basis: the initial main size of the flex item, before free space is distributed according to the flex factors. When omitted from the ‘flex’ shorthand, its specified value is 0%.

If the specified ‘flex-basis’ is ‘main-size’, the used flex basis is the computed value of the flex item’s main size property.

There's a diagram at the w3.org url above that makes it really easy to understand all of the above. Worth a look.

Moto
  • 1,131
  • 2
  • 10
  • 15