The Book of CSS3 - A Developer\'s Guide to the Future of Web Design (2nd edition)

(C. Jardin) #1
Flexible Box Layout 191

The flex-shrink Property


Just as flex-grow is used to expand flex items to fill their container, flex-shrink
is used to shrink items. For example, let’s revisit our flex container from the
previous section with items #a, #b, and #c; only in this case, we’ll make each
item 300px wide. Now the total width of the three items is 900px, which
exceeds the 600px width of the parent by 300px.
To shrink these elements to fit within the container width, you could
use the flex-shrink property:

.flex-item { flex-shrink: 1; }

The flex-shrink property works like flex-grow but in the opposite direc-
tion. For example, a value of 1 (the default) reduces each item by the same
proportion—each by 100px (300 divided by 3). The resulting items will be
200px each, for a total of 600px, which matches the width of the container.
Like flex-grow, different values change the distribution ratio. For
example, if you use a value of 3 for item #b, its width is reduced by three
pixels for every one-pixel reduction of the other two items.

#b { flex-shrink: 3; }

Higher numbers reduce the elements by a greater factor. In this example,
for each pixel removed from the width of #a and #c, three are removed from
#b. As you can see in Figure 15-8, #a and #c are 240px in width, whereas #b is
only 120px, which is narrower than its original width.

Figure 15-8: Flex item #b has a higher flex-shrink value than its siblings, so it’s shrunk
proportionally more to fit its container.

The flex-basis Property


The width of flex items can be set either by the content they contain or by
an explicit width value, and any growth or shrinkage is calculated from that
base width. To change how the width adjustment is calculated, you can set a
flex-basis value on an element. This property takes as a value a length unit.
Here’s an example:

.flex-item { flex-basis: 100px; }
Free download pdf