CSS flex property
The CSS flex
property is a shorthand property that combines three individual Flexbox properties: flex-grow
, flex-shrink
, and flex-basis
. It allows you to set these three values in a single line, making it more concise and convenient to define the flex behavior of a flex item inside a flex container.
Here’s the syntax of the flex
property:
flex: <flex-grow> <flex-shrink> <flex-basis>;
Let’s briefly explain each part of the flex
property:
flex-grow
: This property defines how much a flex item should grow relative to other flex items inside the same flex container if there’s extra space available along the main axis. It takes a unitless number as its value, indicating the proportion of available space that the flex item should take. Aflex-grow
value of 0 means the item won’t grow, while a value of 1 will take up all available space.flex-shrink
: This property specifies how much a flex item should shrink relative to other flex items if there’s not enough space available along the main axis. Likeflex-grow
, it also takes a unitless number as its value. Aflex-shrink
value of 0 means the item won’t shrink, while a value greater than 0 indicates the item’s relative ability to shrink.flex-basis
: This property sets the initial size of the flex item along the main axis before any remaining space is distributed. It can take a length value (e.g.,px
,em
,%
) or the keywordauto
. The default value isauto
, which means the item’s size will be determined by its content.
Here’s an example of using the flex
property:
.flex-item {
flex: 1 0 200px;
}
In this example, the .flex-item
class will have the following flex behavior:
flex-grow
: 1 (The item will grow and take up all available space along the main axis if there’s any excess space).flex-shrink
: 0 (The item won’t shrink if there’s not enough space along the main axis).flex-basis
: 200px (The initial size of the item along the main axis is set to 200 pixels).
Using the flex
property is particularly useful when you want to apply the same flex behavior to multiple flex items in a compact manner. However, if you need more control over each individual property, you can still use the flex-grow
, flex-shrink
, and flex-basis
properties separately.