The display: flex in CSS


The CSS property display: flex is a shorthand for the Flexible Box Module, or Flexbox. Flexbox is a layout model in CSS that allows for the creation of responsive and flexible layouts.

It provides a way to align and distribute space among items in a container, making it easier to create complex layouts without the need for floats or positioning.

css-flexbox-property


What is display: flex?

The display: flex property is used to create a flex container. When an element is set to display: flex, it becomes a flex container, and its direct children become flex items. Flexbox properties can then be used to control the layout of these items and their alignment within the container.

 

Syntax

.container {
  display: flex;
} 
  • .container is the flex container.
  • All direct children inside the container are automatically treated as flex items.

Example

<!DOCTYPE html>
<html lang="en">
<head>
  <style>
    .container {
      display: flex;
      justify-content: space-around; /* Distribute items evenly */
      align-items: center; /* Center items vertically */
      height: 100vh;
      background-color: lightgray;
    }

    .item {
      width: 100px;
      height: 100px;
      background-color: lightblue;
      margin: 10px;
    }

    .item1 {
      flex-grow: 1;
    }

    .item2 {
      flex-basis: 200px;
    }

    .item3 {
      order: 2;
    }
  </style>
</head>
<body>

<div class="container">
  <div class="item item1">Item 1</div>
  <div class="item item2">Item 2</div>
  <div class="item item3">Item 3</div>
</div>

</body>
</html> 



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.