CSS flex

The CSS flex property is used as shorthand for the flex-grow, flex-shrink, and flex-basis properties. For example:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      .container{display: flex;}
      .container > div{border: 1px solid coral; padding: 12px;}
      #secondiv{flex: 0 0 180px;}
   </style>
</head>
<body>

   <div class="container">
      <div>A</div>
      <div id="secondiv">B</div>
      <div>C</div>
      <div>D</div>
   </div>
   
</body>
</html>
Output
A
B
C
D

The CSS rule

.container{display: flex;}

specifies that the container element should use the flexbox layout model, which is a powerful tool for creating flexible and responsive layouts.

The CSS rule

.container > div{border: 1px solid coral; padding: 12px;}

applies to all immediate child div elements of the container element, and sets a solid coral border with a thickness of 1px and a padding of 12px.

The CSS rule

#secondiv{flex: 0 0 180px;}

applies specifically to the div element with the ID "secondiv", and sets the flex property to

flex: 0 0 180px;

This means that this div should not grow or shrink when the container is resized (flex-grow: 0; flex-shrink: 0;), and it should have a fixed width of 180 pixels (flex-basis: 180px;). This can be useful for creating a fixed-width sidebar or column within a flexible layout.

CSS flex syntax

The syntax of the "flex" property in CSS is:

flex: flex-grow flex-shrink flex-basis|auto|initial|inherit;

Note: To define flex-grow and flex-shrink, we use numbers like 1, 2, 3, etc. Whereas to define flex-basis, we use length, e.g., 200px.

When we use auto, then the property is defined in this way:

flex: 1 1 auto

When we use initial, the property is defined in this way:

0 1 auto

When we use none, the property is defined in this way:

0 0 auto

And we use inherit to use the value inherited by the parent element.

CSS Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!