1. css
  2. /properties
  3. /flex

flex

Definition

flex is a shorthand property in CSS that sets the flex-grow, flex-shrink, and flex-basis properties of a flex item in a single declaration. It sets the flexibility of a flex item and determines the amount of space it should occupy in the main axis of its container.

Examples

In this example, flex: 1 sets the flex-grow property to 1, which means the item will occupy one unit of the available space in its container:

.item {
  flex: 1;
}

In this example, flex: 2 2 200px sets the flex-grow property to 2, the flex-shrink property to 2, and the flex-basis property to 200px. The item will occupy two units of the available space and will shrink by two units if there is not enough space. The initial size of the item will be 200px:

.item {
  flex: 2 2 200px;
}

In this example, flex: 0 1 auto sets the flex-grow property to 0, the flex-shrink property to 1, and the flex-basis property to auto. The item will not grow, but it will shrink by one unit if there is not enough space. The initial size of the item will be based on its content.

Values

ValueDescription
flex: <flex-grow> <flex-shrink> <flex-basis>A shorthand property that sets the flex-grow, flex-shrink, and flex-basis properties. The default value is 0 1 auto.
initialSets the property to its default value.
inheritInherits the property from its parent element.

Best Practices

  • Use the flex property to set the flexibility of a flex item in a single declaration.
  • Use the flex-grow property to determine the amount of space the item should occupy in the main axis of its container.
  • Use the flex-shrink property to determine the amount by which the item should shrink if there is not enough space.
  • Use the flex-basis property to set the initial size of the item.
  • Test your code in different screen sizes and browsers to ensure that it works as intended.

Browser Compatibility

ChromeFirefoxSafariInternet ExplorerMicrosoft EdgeOpera
YesYesYesYesYesYes