CSS Flexbox - Responsive



In CSS, responsive flexbox refers to designing flexible and adaptable layouts that automatically adjusts the placement, alignment, and sizing of elements within a container based on the available screen space.

CSS Responsive Flexbox - Using flex-direction

The following example shows a two-column layout for large screens and a single-column layout for small screens like phones and tablets. We can change the flex-direction to switch from a horizontal to a vertical layout at a selected breakpoint, such as 400px.

<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
   .flex_responsive {
      display: flex;
      text-align: center;
   }
   .flex_responsive div {
      width: 50%;
      padding: 10px;
      box-sizing: border-box;
      background-color: yellow;
      border: 3px solid green;
   }
   @media (max-width: 400px) {
      .flex_responsive {
         flex-direction: column;
      }
   }
</style>
</head>
<body>
   <h2>Resize the browser window to see the effect</h2>
   <div class="flex_responsive">
      <div>Flex item 1</div>
      <div>Flex item 2</div>
      <div>Flex item 3</div>
   </div>
</body>
</html>

CSS Responsive Flexbox - Using flex-wrap

You can use the flex property by adjusting the percentage values of flex items to achieve different layouts for different screen sizes.

It's essential to include flex-wrap: wrap within the flex container.

Let us see an example −

<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
   * {
      box-sizing: border-box;
   }
   .flex_responsive {
      display: flex;
      flex-wrap: wrap;
      text-align: center;
   }
   .flex_responsive div {
      padding: 10px;
      flex: 33.33%;
      background-color: yellow;
      border: 3px solid green;
   }
   @media (max-width: 500px) {
      .flex-item {
         flex: 90%;
      }
   }
</style>
</head>
<body>
   <h2>Resize the browser window to see the effect</h2>
   <div class="flex_responsive">
      <div>Flex item 1</div>
      <div>Flex item 2</div>
      <div>Flex item 3</div>
   </div>
</body>
</html>
Advertisements