Align Flex Items along Cross Axis using CSS3


We can easily align the flex items along cross axis, but first let us understand what cross axis is. The cross axis is perpendicular to the main axis. The main axis is like the flex direction −

Create a Container div

First, set the divs inside a container(flex container) −

<div class="container">
   <div class="first">First Div</div>
   <div class="second">Second Div</div>
   <div class="third">Third Div</div>
</div>

Style the Container and Make it Flexible

The flex container becomes flexible by setting the display property to flex. The flex items are aligned using the align-items property −

.container {
   height: 200px;
   display: flex;
   width: 100%;
   align-items: center;
   border: 2px solid red;
}

Style the Flex Items

The individual flex items styled with different background colors −

.first {
   background-color: rgb(55, 0, 255);
}
.second {
   background-color: red;
}
.third {
   background-color: rgb(140, 0, 255);
}

Align Flex Items Along Cross Axis

Example

To align Flex Items along Cross Axis using CSS3, the code is as follows −

<!DOCTYPE html>
<html>
<head>
   <style>
      body {
         font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
      }
      .container {
         height: 200px;
         display: flex;
         width: 100%;
         align-items: center;
         border: 2px solid red;
      }
      div {
         width: 100px;
         height: 100px;
         color: white;
         text-align: center;
         font-size: 30px;
      }
      .first {
         background-color: rgb(55, 0, 255);
      }
      .second {
         background-color: red;
      }
      .third {
         background-color: rgb(140, 0, 255);
      }
   </style>
</head>
<body>
   <h1>Align flex items along cross axis</h1>
   <div class="container">
      <div class="first">First Div</div>
      <div class="second">Second Div</div>
      <div class="third">Third Div</div>
   </div>
</body>
</html>

Updated on: 27-Oct-2023

77 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements