Controlling the Size of Flex Items in CSS

How flex items should be sized relative to other flex items in response to changes in the browser window’s size is specified with three factors: the initial size of an item, how much it should grow when there is more space, and how much it should shrink when there is less space. These factors work together to dynamically size an item, and each can either be specified singly (using longhand properties) or together with others (using a shorthand property).

1. Specifying Flex Items Sizing Factors Individually

The properties for specifying the sizing factors for flex items individually are flex-grow, flex-shrink, and flex-basis longhand properties. They apply to only individual flex items and are, therefore, specified in rules targeting individual flex items rather than those targeting all the items within a flex container. Table 19.3 lists their function. The best way to see and understand how they work is through implementing them and varying the values and the width of the browser. So, this has been left as a challenge.

2. Specifying All Flex Items Sizing Factors with One Property

The property for specifying flex-grow, flex-shrink, and flex-basis longhand properties together is the flex shorthand property. When used to specify the properties, values are specified in the order flex-grow, flex-shrink, and flex- basis (e.g., flex: 3 2 15%), but only flex-grow is mandatory. The property can also take none or auto keyword. When flex-grow is omitted, it is set to 1; when flex-shrink is omitted, it is set to 1; and when flex-basis is omitted, it is set to 0. Table 19.4 shows examples of the common ways values are specified and Figure 19.8 shows how the property is used.

In the .flex-container {} rule in the example, the display property makes the <div> element of class=“flex-container” a flex container and the border property makes its border 2px-thick black solid line. The .flex-container div{} rule styles the <div> elements (i.e., the flex items) inside the flex container, giving them background color, padding to make them bigger, 2px-thick grey border, and horizontally center-aligning their contents. The .one{} and .two{} rules each specifies the flex-grow, flex-shrink, and flex- basis properties. These three properties work together to specify that the <div> element of class=“two” (i.e., item 2) should take five times more space than the <div> element of class=“one” (i.e., item 1) when there is enough space, and take three times less space when there is not enough space.

2.1. Vertical Space Example

Figure 19.9 shows a practical example in which elements are vertically flowed and sized with the flex property and Figure 19.10 the result.

Source: Sklar David (2016), HTML: A Gentle Introduction to the Web’s Most Popular Language, O’Reilly Media; 1st edition.

Leave a Reply

Your email address will not be published. Required fields are marked *