CSS Flexbox - flex Property



CSS flex property defines how the flex items grow, shrink, and allocate space along the flex container. This property is a shorthand for the following CSS properties:

Possible Values

  • initial− The item is sized according to its width and height properties. Its equivalent to flex: 0 1 auto
  • auto − The item's size is determine by its width and height properties, expands to fill extra space in the flex container, and shrink to its minimum size to fit the container. It is equal to flex: 1 1 auto.

  • none − The item's size remains fixed and does not expand or shrink when the flex container's dimensions change. It is equal to flex: 0 0 auto.

  • <'flex-grow'> − A number specifying how much the item will grow relative to the rest of the flexible items

  • <'flex-shrink'>− A number specifying how much the item will shrink relative to the rest of the flexible items.

  • <'flex-basis'> − The length of the item. (auto,%,px,em etc)

Applies to

Flex items, including in-flow pseudo-elements

DOM Syntax

object.style.flex = "auto|none|<number>";

CSS Flex - auto Value

The following example demonstrates that flex: auto property grow and shrink the flex item equally to fill the available space −

<html>
<head>
<style>
   .flex-container {
      display: flex;
      background-color: green;
   }
   .flex-container>div {
      background-color: yellow;
      margin: 10px;
      padding: 15px;
      flex: auto;
   }
</style>
</head>
<body>
   <div class="flex-container">
      <div>Flex item 1</div>
      <div>Flex item 2</div>
      <div>Flex item 3</div>
   </div>
</body>
</html>

CSS Flex - none Value

The following example demonstrates that flex: none property prevents the flex items from growing or shriking to fill the available space −

<html>
<head>
<style>
   .flex-container {
      display: flex;
      background-color: green;
   }
   .flex-container>div {
      background-color: yellow;
      margin: 10px;
      padding: 15px;
      flex: none;
   }
</style>
</head>
<body>
   <div class="flex-container">
      <div>Flex item 1</div>
      <div>Flex item 2</div>
      <div>Flex item 3</div>
   </div>
</body>
</html>

CSS Flex - <number> Value

The following example demonstrates that flex: 2 property the second grid item will take up two times the space of the other flex items in the flex container −

<html>
<head>
<style>
   .flex-container {
      display: flex;
      background-color: green; 
   }
   .flex-container>div {
      background-color: yellow;
      margin: 10px;
      padding: 15px;
   }
   .flex-item2 {
      flex: 2;
   }
</style>
</head>
<body>
   <div class="flex-container">
      <div>Flex item 1</div>
      <div class="flex-item2">Flex item 2</div>
      <div>Flex item 3</div>
   </div>
</body>
</html>
Advertisements