I'm starting to work with flexbox, and, in order to understand flex-grow
and flex-shrink
, I used a simple program that displays two blocks and makes them take up the whole width using flex-grow: 2
in one of them and flex-grow: 1
in the other.
If I check the following line in the console: $(".one").width() === $(window).width() /3
it returns true. So far, so good.
The problem appears when I reduce the window size, because as soon as I do this the same line in the console ($(".one").width() === $(window).width() /3
) starts returning false.
I know the default value for flex-shrink
is 1
. Wouldn't that mean that the proportions between both blocks would be maintained (since they are both being shrunk by the same amount)? Can anyone explain why this result happens?
Here's my code:
* {
font-family: verdana;
margin: 0;
}
body {
background: #eee;
}
.wrapper {
width: 100%;
max-width: 2000px;
margin: 0 auto;
}
.flex-container {
display: flex;
background-color: white;
}
.box {
height: 100px;
}
.one {
background-color: red;
flex-grow: 1;
}
.two {
background-color: blue;
flex-grow: 2;
}
<div class="wrapper">
<div class="flex-container">
<div class="box one"></div>
<div class="box two"></div>
</div>
</div>
Firstly, you can't apply a fixed width AND flex-grow. Secondly, flex-grow only works if the parent element has display:flex . In this case the section has display flex but the links do not and the flexgrow divs are children of the link…not the section.
A flexbox item can be set to a fixed width by setting 3 CSS properties — flex-basis, flex-grow & flex-shrink. flex-basis : This property specifies the initial length of the flex item. flex-grow : This property specifies how much the flex item will grow relative to the rest of the flex items.
The default value for flex-shrink is 1 — that means your elements will shrink until you tell them not to! Again, flex-shrink is about proportions. If one box has flex-shrink of 6, and the rest have flex-shrink of 2, the one box will shrink 3x as fast as the rest, as space compresses.
You can easily shrink an image by using the flex-wrap property in CSS and it specifies whether flex items are forced into a single line or wrapped onto multiple lines. The flex-wrap property allows enabling the control direction in which lines are stacked.
While not relevant to your question it might be worth noting:
flex-wrap
takes precedence overflex-shrink
, unless the item is wider than the container.
See also Is there any use for flex-shrink when flex-wrap is wrap?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With