Control of Flexbox Item Relationships in Main Direction

css control flex item ratios main axis
10 November 2024

Using Flexbox in CSS is a significant step towards designing responsive layouts and adaptive elements. Flexbox allows us to easily organize items in a container and control their relationships in the main direction. Utilizing Flexbox features like flex-grow, flex-shrink, and flex-basis enables us to determine the relationships of the items.

When you want items in a flex container to proportionally change their size, flex-grow is the most important feature. This feature indicates how much each item can use the remaining space. Similarly, flex-shrink specifies how items can reduce their size relative to their own space so that they fit within the container.

Correct use of these features can help you build a layout that dynamically adjusts to the dimensions of the display screen or any other changes, without forcing you to use fixed dimensions.

Here’s an example of using these features:


    <style>
      .container {
        display: flex;
      }
      .item {
        flex-grow: 1;
        flex-shrink: 1;
        flex-basis: 100px;
        margin: 10px;
        background-color: lightblue;
      }
    </style>
    <div class="container">
      <div class="item">Item 1</div>
      <div class="item">Item 2</div>
      <div class="item">Item 3</div>
    </div>
  

Description

.container: <br> This class applies display: flex; to the main container to allow it to act as a flexbox.
.item: <br> Each item has three main properties for flex.
flex-grow: 1;: <br> Items can proportionally distribute the extra space among themselves.
flex-shrink: 1;: <br> If the container space is reduced, each item will proportionally shrink from its own space.
flex-basis: 100px;: <br> The initial size of each item is 100 pixels.
margin: 10px; and background-color: lightblue;: <br> For spacing and a beautiful background color.

FAQ

?

Why should we use Flexbox?

?

What does flex-grow do?

?

Is Flexbox a replacement for CSS Grid?